Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 489
Targaryen Avatar asked Aug 14 '26 05:08

Targaryen


2 Answers

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 });
});
like image 188
Targaryen Avatar answered Aug 16 '26 20:08

Targaryen


A better solution may be to use a custom error matcher.

Here's an example of using a class property to decide when the error should be shown: http://plnkr.co/edit/U5xtdKWggcbgU2EHKkK9?p=preview

<md-form-field>
  <input mdInput [formControl]="myInput" placeholder="My Input" [errorStateMatcher]="showWhenISayTo">
  <md-error>Field is required</md-error>
</md-form-field>


// Set this to `true` to show the errors
showError = false;

myInput = new FormControl('', Validators.required)

showWhenISayTo = () => {
  return this.showError;
}

Also, you can configure it to use the same behavior globally. Here's an example of showing errors as soon as the invalid control is dirty: http://plnkr.co/edit/gcQuzYChrl5d7UYXo8eS?p=preview

import {MD_ERROR_GLOBAL_OPTIONS, showOnDirtyErrorStateMatcher} from '@angular/material';

@NgModule({
  providers: [
    {provide: MD_ERROR_GLOBAL_OPTIONS, useValue: {errorStateMatcher: showOnDirtyErrorStateMatcher}}
  ]
})
like image 28
Will Howell Avatar answered Aug 16 '26 20:08

Will Howell