Hap*_*der 2 forms validation angular
我有一个表格如下:
<form [formGroup]="editProfileForm">
<input type="text" id="name" class="form-control" placeholder="First" formControlName="firstName [(ngModel)]="profileDetails.first_name">
<small class="text-danger" [hidden]="editProfileForm.controls['firstName'].valid || (editProfileForm.controls['firstName'].pristine && !submitted)">First name Required</small>
<input type="text" class="form-control" placeholder="Last" formControlName="lastName" [(ngModel)]="profileDetails.last_name">
<small class="text-danger" [hidden]="editProfileForm.controls['lastName'].valid || (editProfileForm.controls['lastName'].pristine && !submitted)">Last name Required</small>
<button class="save-changes-btn" [disabled]="(!editProfileForm.valid)" (click)="saveDetails();">Save Changes</button>
</form>
Run Code Online (Sandbox Code Playgroud)
并且 editProfile 在组件文件中定义为
this.editProfileForm = this.formBuilder.group({
firstName: [_.get(this.profileDetails, 'first_name', ''), Validators.required],
lastName: [_.get(this.profileDetails, 'last_name', ''), Validators.required],
});
Run Code Online (Sandbox Code Playgroud)
现在我需要在单击提交按钮时显示验证消息。现在,如果表单无效,我已禁用提交按钮。但是它不会在相应字段附近显示错误消息,这会使用户认为没有任何事情发生。如何触发错误消息以在相应的输入字段附近显示?
est*_*art 27
保存时,如果表单无效,只需调用markAllAsTouched()表单组即可。
saveDetails() {
if(!this.editProfileForm.valid) {
this.editProfileForm.markAllAsTouched();
}
}
Run Code Online (Sandbox Code Playgroud)
你可以做这样的事情。
首先删除提交按钮中的禁用逻辑。
在组件模板中。
<form [formGroup]="editProfileForm" (ngSubmit)="onSubmit()">
<div class="form-group block" [ngClass]="{'has-error': submitted && (editProfileForm.controls.firstName.errors)}">
<label>Email</label>
<input type="text" class="form-control" formControlName="firstName">
<p>
<span *ngIf="submitted && editProfileForm.controls.firstName.errors?.required">First name is required</span>
</p>
</div>
// other controls
</form>
Run Code Online (Sandbox Code Playgroud)
在组件类中
public onSubmit(): void {
this.submitted = true;
if(!this.editProfileForm.valid) {
return;
}
// make the submitted variable false when submission is completed.
}
Run Code Online (Sandbox Code Playgroud)
如果需要,您可以删除以下部分。
[ngClass]="{'has-error': submitted && (editProfileForm.controls.firstName.errors)}"
Run Code Online (Sandbox Code Playgroud)
当表单控件无效并提交时,它将向元素添加css类。
使用showValidationMsg()方法并将表单组作为参数传递给提交按钮方法:
showValidationMsg(formGroup: FormGroup) {
for (const key in formGroup.controls) {
if (formGroup.controls.hasOwnProperty(key)) {
const control: FormControl = <FormControl>formGroup.controls[key];
if (Object.keys(control).includes('controls')) {
const formGroupChild: FormGroup = <FormGroup>formGroup.controls[key];
this.showValidationMsg(formGroupChild);
}
control.markAsTouched();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13252 次 |
| 最近记录: |