【发布时间】:2021-11-16 13:46:07
【问题描述】:
Stackblitz https://stackblitz.com/edit/angular-mh4cox?embed=1&file=src/app/app.component.html
如何在嵌套表单上正确显示错误消息? 验证工作顺便说一句
我在这里尝试了很多方法,但没有任何运气。
我希望它使用 ngIF 在 html 上显示错误消息(... invalid && ... added )
构造函数
constructor(private fb: FormBuilder,private http:HttpClient,private requestService:RequestService) {
this.myForm = this.fb.group({
id:[""],
areaOfInterest: new FormControl("",Validators.required),
status: new FormControl("",Validators.required),
startDate: new FormControl("",Validators.required),
endDate: new FormControl("",Validators.required),
description: new FormControl("",Validators.required),
notes: new FormControl("",Validators.required),
createdBy:"",
updatedBy:"",
resourceDTOS: this.fb.array([]),
});
console.log(this.myForm);
this.getOneRequest(localStorage.getItem('requestId'));
}
这是嵌套资源,在这种情况下是 FormArray
addNewResourceDTOS() {
this.control = <FormArray>this.myForm.controls.resourceDTOS;
this.control.push(
this.fb.group({
seniority: this.fb.control(null,Validators.required),
skillDTOS: this.fb.array([this.fb.group({
skill: '' //i dont validate it here
})]),
resourceNotes: this.fb.control(null,Validators.required),
})
);
}
数组技能DTOS
addNewResourceSkill(control) {
control.push(
this.fb.group({
skill: new FormControl("",Validators.required),
}))
}
这就是我验证一些主要表单变量的方式
get description() {
return this.myForm.get('description');
}
get notes() {
return this.myForm.get('notes');
}
示例 html“注释”
<small *ngIf="notes.invalid && notes.touched" class="text-danger">Please enter notes!</small>
看起来像这样
data = {
areaOfInterest:"",
notes:"",
resourceDTOS: [
{
seniority: "",
skillDTOS: [
{
skill: "",
}
],
resourceNotes:""
}
]
}
是否也可以至少验证资历/资源说明(或最好的技能)?
【问题讨论】:
-
对不起,描述不清楚。从您的代码中,我看到验证完全正确。验证适用于资历、resourceNotes 和技能字段(不包括第一项技能)。
-
但我的目标是在无效时显示错误消息。可能吗?与主要的表单变量一样,例如描述
标签: angular