gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:51:31 25 4
gpt4 key购买 nike

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

enter image description here

最佳答案

你可以这样强制

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

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

this.form.markAllAsTouched();

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

关于angular - 在触摸控件之前显示 mat-form-field 错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62852352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com