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.
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
usingerrorStateMatcher
input property on input element.So implement the following
ErrorStateMatcher
in your codeAnd you could modify
isErrorState()
as followsAnd place your
mat-error
andinput
tag inside the samemat-form-field