Angular Material无法设置hasErrors(始终为空)

时间:2018-03-20 11:57:43

标签: angular angular-material2

我的例子https://stackblitz.com/edit/angular-unxe7d?file=app%2Finput-error-state-matcher-example.ts

我试图在formControl上设置hasErrors,我在matFormField中使用它。 像这样:

@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 });
  }
}

但是emailFormControl.hasError(&#39;不正确&#39;)始终为false,并且emailFormControl.valid为true。这是错误的行为还是我做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试使用ngAfterViewInit()代替ngOnInit

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