multiple mat-error for formArray unable to figureout

Viewed 2126

I want to have multiple error messages and unable to figure out how to do so..? Here I need to validate each step separately so that's why I am using this stepper

<form [formGroup]="formGroup" method="POST" #f="ngForm">
    <mat-vertical-stepper #linearVerticalStepper="matVerticalStepper" formArrayName="formArray" [linear]="true">
        <mat-step formGroupName="0" [stepControl]="formArray?.get([0])">
            <mat-form-field>
               <mat-label>Email</mat-label>
               <input matInput formControlName="emailCtrl" required>
               <mat-error>This field is required</mat-error>
               <mat-error>Invalid Email</mat-error>
            </mat-form-field>
        </mat-step>
   </mat-vertical-stepper>
</form>

and form builder is:-

ngOnInit() {
    this.formGroup = this._formBuilder.group({
      formArray: this._formBuilder.array([
        this._formBuilder.group({
          emailCtrl: [
            "",[
            Validators.required,     

//This field is required

            Validators.pattern(
              "^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$" 

// Invalid Email Provided

            )]
          ],
        }),
      ])
    });
  }
2 Answers

I knwo it's too late. But i think it will be helpful for future refrences. It's in their official example .If you take a close look on their email validation error message it will be like this.

 <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error

and in in ts file you have to define the messages which you want to show accroding to the error

getErrorMessage() {
if (this.email.hasError('required')) {
  return 'You must enter a value';
}

return this.email.hasError('email') ? 'Not a valid email' : '';
  }
Related