Search code examples
angularangular-materialangular-forms

Can the Angular Material ErrorStateMatcher detect when a parent form is submitted?


I have a parent component that sets up a form and passes it down to a child component.

<form [formGroup]="form" (submit)="submit()">
  <app-child [form]="form"></app-child>
  <button mat-button type="submit">Submit</button>
</form>

The child component displays an input field like this:

<mat-form-field *ngIf="form" [formGroup]="form">
  <input matInput
         placeholder="Email"
         formControlName="email"
         [errorStateMatcher]="matcher"
         required>
</mat-form-field>

The input field is required and should show an error if the form is submitted without filling it in, even if the user never touched it. This is the automatic behavior in a simple form, but (I think) since I am using a child form, I have to implement custom error logic with ErrorStateMatcher.

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control, form) {
    return control && control.invalid && form && form.submitted;
  }
}

However, this doesn't work. I can't figure out how to get the child input to detect when the parent form has been submitted. The ErrorStateMatcher detects that something has changed, but the submitted property of form is always false. What am I doing wrong?

See this Stackblitz


Solution

  • you don't need to implement ErrorStateMatcher to achieve such behavior. and it doesn't make sense to use formGroup on a mat-form-field

    Just change child.component.html as follows

    <mat-form-field *ngIf="form">
      <input matInput placeholder="Email" [formControl]="form.get('email')">
    </mat-form-field>
    

    here is a working example https://stackblitz.com/edit/angular-material-error-matcher-child-component-6nwmwe