我在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上的验证错误,而不是在输入模糊和触摸时 .
1 回答
我最近回答了类似的问题here . 请看一下 . 它有点工作,但非常有帮助 .
要实现所需,您必须使用输入元素上的
errorStateMatcher
input属性覆盖mat-error
的默认行为 .因此,在代码中实现以下
ErrorStateMatcher
您可以按如下方式修改
isErrorState()
并将
mat-error
和input
标记放在同一个mat-form-field
中