0
votes

My example here https://stackblitz.com/edit/angular-unxe7d?file=app%2Finput-error-state-matcher-example.ts

I'm trying to set hasErrors on formControl which I use in matFormField. Like this:

@Component({
  selector: 'input-error-state-matcher-example',
  template: `<form class="example-form">
              <mat-form-field class="example-full-width">
                <input matInput
                      placeholder="Email" 
                      [formControl]="emailFormControl">
              </mat-form-field>
    {{emailFormControl.hasError('incorrect')}} 
  {{emailFormControl.valid}} 
</form>`,
  styleUrls: ['./input-error-state-matcher-example.css'],
})
export class InputErrorStateMatcherExample implements OnInit {
  emailFormControl = new FormControl('');

  ngOnInit() {
    this.emailFormControl.setErrors({ 'incorrect': true });
  }
}

But emailFormControl.hasError('incorrect') always false and emailFormControl.valid is true. Is this wrong behavior or I doing something wrong?

1
Having the code of your stackblitz would be better than having the demonstration only. - user4676340
@trichetriche i fixed link - user2696126
great, but I already provided you a working answer if you care to look at it - user4676340
And please, mark your issue as resolved. We helped you, the least you can do is notify future users looking for answers that you actually resolved your issue. - user4676340

1 Answers

0
votes

Try using ngAfterViewInit() instead of ngOnInit.

  ngAfterViewInit() {
    this.emailFormControl.setErrors({ 'incorrect': true });
  }