我正在做一个嵌套的反应式形式。当表单控件位于不同的组件中时,有一个关于自动设置将字段标记为无效(使用红色(的类的未决问题。
这些类是mat-form-field-invalid
和mat-input-invalid
。
因此,我解决这个问题的想法是在单击提交按钮后从 FormGroup 获取无效控件,并在循环中将它们与无效控件/字段的 formControlName 匹配,并以编程方式将它们设置为无效。
我尝试了formData.form.controls['formControlName'].markAsTouched();
和我在这里找到的其他类似"解决方案"并谷歌搜索,但它们中的任何一个都有效。
我该怎么做?
我正在使用角度材质 5.2.4。
最后,我做了什么来将 CSS 错误类添加到在我的嵌套反应式表单中无效的字段中:
this.invalidControls(this.formGroup); //Call it just after submit the form
//The implementation of the function
invalidControls(name): void {
for (const field in name.controls) {
const control = name.get(field);
if(control.constructor.name == "FormArray" || control.constructor.name == "FormGroup"){
this.invalidControls(control); //If the AbstractControl is not a FormControl the funtion will be called again
}
else{
if(control.status === "INVALID"){
control.markAsTouched({ onlySelf: true });
control.markAsDirty({ onlySelf: true });
}
}
}
}
因此,如果将控件设置为无效、脏且为空,则将添加 CSS 错误类。否则不会。