在触摸控件之前显示 mat-form-field 错误消息

Display mat-form-field error message before control is touched

这个问题有一个 Stackblitz; stackblitz.com/edit/yz1dhz.

如何在加载组件时和用户触摸控件之前呈现 mat-form-field 验证错误消息?

class AppComponent implements OnInit {
  form: FormGroup;

  constructor(private readonly fb: FormBuilder) {
    // Create a form in an invalid state.
    this.form = this.fb.group({
      a: this.fb.control(null, [Validators.required])
    });
  }

  ngOnInit() {
    // This does do what I had hoped.
    this.form.updateValueAndValidity();
  }
}

该代码创建的表单立即无效。我希望 <mat-error> 显示:

<form [formGroup]="form">
    <mat-form-field>
        <mat-select formControlName="a">
            <mat-option>Foo</mat-option>
            <mat-option>Bar</mat-option>
            <mat-option>Baz</mat-option>
        </mat-select>
    <mat-hint>I am a hint.</mat-hint>
    <mat-error>{{ form.controls['a'].errors | json }}</mat-error>
    </mat-form-field>
</form>

而是显示 <mat-hint>

你可以这样强制

this.form.get('a').markAsTouched();

或者您可以将所有控件标记为已触摸

this.form.markAllAsTouched();

您可以使用 markAsTouched、markAllAsTouched、markAsUntouched、markAsDirty、markAsPristine、markAsPending...

更改表单控件的状态