首页 文章

当matInput失去焦点时,如何避免mat-form-field验证触发器?

提问于
浏览
1

我在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 回答

  • 0

    我最近回答了类似的问题here . 请看一下 . 它有点工作,但非常有帮助 .

    要实现所需,您必须使用输入元素上的 errorStateMatcher input属性覆盖 mat-error 的默认行为 .

    因此,在代码中实现以下 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-errorinput 标记放在同一个 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>
    

相关问题