每个使用 mat-select 作为唯一必填字段的 formGroup 不能使用 FormGroup.reset() 重置,因为验证器不会重置
提交时,第一个字段为空并标记为错误...
唯一对我有用的解决方案是使用 ngIf 重新生成表单,但对于看到空 html 的用户来说并不是很好......
还有其他解决方案吗?
谢谢!
最佳答案
由于已经有一个被接受的答案,我可以建议在那里添加较少的行。
这是 Material
的一个众所周知的错误,作为解决方法,您可以将 ElementReference
添加到您的 form
标记 #f="ngForm"
:
<form [formGroup]="quickFileForm" (ngSubmit)="saveQuickFileForm()" #f="ngForm">
然后将 @ViewChild
装饰器添加到引用表单中标记的 TS 部分:
import { Component, ViewChild } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
group = new FormGroup({
select: new FormControl(null, Validators.required),
input: new FormControl()
});
@ViewChild('f') myForm;
....
....
}
不要忘记从 @angular/core
导入它。然后只需添加:
this.myForm.resetForm();
你的方法:
submit() {
if(this.group.valid) {
const obj = new MyObj();
Object.assign(obj, this.group.value);
this.survey.push(obj);
this.myForm.resetForm(); // <-- Here you add it.
return;
}
alert('not valid, try again')
}
关于angular - 所需的垫选择无法重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53522364/