How to avoid mat-form-field Validation trigger whe

2019-07-22 07:15发布

I have the following FormGroup in createGroup.component.ts

    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, [
  ])
});

I have the below angular html that uses material directives in 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>

The problem is, when cursor out focus the input, the formGroup validation gets triggered. enter image description here

I need to trigger validation errors on mat-form-field only if the user pressed submit or the input is dirty, not when input is blur and touched.

1条回答
该账号已被封号
2楼-- · 2019-07-22 07:46

I recently answered the similar question here. Please have a look at that. Its a little work around but very helpful.

To achieve what you want, you have to override the default behavior of mat-error using errorStateMatcher input property on input element.

So implement the following ErrorStateMatcher in your code

And you could modify isErrorState() as follows

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
  }
}

And place your mat-error and input tag inside the same 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>
查看更多
登录 后发表回答