Search code examples
angularangular-material2

Angular Material Trigger Touched State Programmatically


I'm using Angular 4 Reactive Forms with @angular/material version 2.0.0-beta.10. I need to programmatically make the md-error message appear.

On required fields, when a user leaves an input without entering any text, I have an md-error that says, "This field is required." See code:

<md-form-field>
    <input mdInput type="text"
           formControlName="PartNumber"
           placeholder="Part Number"
           maxlength="250"
           required />
    <md-error *ngIf="formGroup.controls['PartNumber'].hasError('required')">
        Part Number is <strong>required</strong>
    </md-error>
</md-form-field>

I've tried both:

this.formGroup.markAsTouched();
this.formGroup.markAsDirty();

The md-error text underneath the <input> does not appear when I call markAsTouched() or markAsDirty().

How do I programmatically trigger a touched state so that the error message appears?


Solution

  • The solution was to loop through each control and mark each one as touched:

    Object.keys(this.formGroup.controls).forEach(key => {
        const ctrl = this.formGroup.get(key);
        ctrl.markAsTouched({ onlySelf: true });
    });