首页 > 解决方案 > 在触摸控件之前显示 mat-form-field 错误消息

问题描述

这个问题有一个 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>显示。

在此处输入图像描述

标签: angularangular-materialangular-formsangular-formbuilder

解决方案


你可以这样强制

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

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

this.form.markAllAsTouched();

您可以使用markAsTouched、markAllAsTouched、markAsUntouched、markAsDirty、markAsPristine、markAsPending更改表单控件的状态...


推荐阅读