【问题标题】:Display mat-form-field error message before control is touched在触摸控件之前显示 mat-form-field 错误消息
【发布时间】:2020-11-01 06:16:43
【问题描述】:

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

但显示的是&lt;mat-hint&gt;

【问题讨论】:

    标签: angular angular-material angular-forms angular-formbuilder


    【解决方案1】:

    你可以这样强迫它

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

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

    this.form.markAllAsTouched();
    

    您可以使用 ma​​rkAsTouched、markAllAsTouched、markAsUntouched、markAsDirty、markAsPristine、markAsPending...

    更改表单控件的状态

    【讨论】:

      猜你喜欢
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 2020-09-05
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      相关资源
      最近更新 更多