我在createGroup.component.ts中有以下FormGroup
this.formGroup = new FormGroup({
groupName: new FormControl({ value: this.data.groupName, disabled: this.isEditPopup }, [
Validators.required
]),
groupDescription: new FormControl(this.data.groupDescription, [
]),
groupId: new FormControl(this.data.groupId, [
])
});
我有下面的角html,它在createGroup.component.html中使用了材料指令
<form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
<mat-form-field>
<input matInput formControlName="groupName" placeholder="Group name*">
</mat-form-field>`enter code here`
<div *ngIf="(formGroup.controls['groupName'].touched)">
<mat-error *ngIf="formGroup.controls['groupName'].hasError('required') ">
Group Name is required
</mat-error>
</div>
<div mat-dialog-actions>
<button mat-button [ngClass]="['btn','btn-success','active']" type="submit">Ok</button>
<button mat-button (click)="cancelDialog($event)" type="button">Cancel</button>
</div>
</form>
问题是,当光标移出焦点时,会触发formGroup验证。 enter image description here
仅当用户按下“提交”或输入内容肮脏时,才需要在mat-form-field上触发验证错误,而不是在输入内容模糊不清时才触发。
答案 0 :(得分:0)
我最近回答了类似的问题here。请看看。它可以解决一些问题,但是非常有帮助。
要实现所需的功能,必须使用输入元素上的mat-error
输入属性来覆盖errorStateMatcher
的默认行为。
因此,请在代码中实现以下ErrorStateMatcher
您可以按如下方式修改isErrorState()
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
return (control && (control.dirty && control.invalid)); // show error only when dirty and invalid
}
}
然后将您的mat-error
和input
标签放在相同的mat-form-field
<mat-form-field>
<input matInput [errorStateMatcher]="matcher" formControlName="groupName" placeholder="Group name*">
<mat-error *ngIf="formGroup.controls['groupName'].hasError('required')">
Group Name is required
</mat-error>
</mat-form-field>