我正在使用带有 Angular Material 的反应形式。 当我单击 onsubmit() 时,我希望所有没有值的参数都不会显示错误(红线)
我尝试使用
this.formGroup.markAsUntouched();
但没用。
当我不在 Angular Material 上使用时,它可以工作。 有人知道如何正确使用 Angular Material 吗?
<form [formGroup]="formGroup" (ngSubmit)="onSubmit(formGroup.value)" class="form">
<mat-form-field class="form-element">
<input matInput placeholder="Emailaddress" formControlName="email">
</mat-form-field>
</form>
onSubmit(post) {
this.formGroup.markAsUntouched();
}
formGroup 将保持不变,但红线仍然出现。
formReset(formGroup: FormGroup) {
formGroup.control.reset();
formGroup.control.markAsPristine();
formGroup.control.markAsUntouched();
}
// for safety measure try calling this function in a try-catch block, it works on a reactive forms
如果出现红色下划线,可以重置所有 FormGroup 错误
this.formGroup.setErrors(null);
使用此方法可以抑制所有错误消息
Object.keys(this.mygroup.controls).map((field) => {
const control = this.mygroup.get(field);
if (control instanceof FormControl) {
control.setErrors(null);
}
});
或者单独抑制任何消息
this.mygroup.controls.frmCtrlMyControl.setErrors(null);
我在具有单个 formControl 的表单中也遇到同样的问题
this.form = this.fb.group({
Email: ['', Validators.required],
})
我尝试了所有建议
this.form.controls.Email.setValue('');
this.form.controls.Email.setErrors(null);
this.form.controls.Email.reset();
this.form.controls.Email.markAsUntouched();
this.form.controls.Email.markAsPristine();
我也尝试过重置表格
this.form.reset();
this.form.setErrors(null);