angular - 角度中的嵌套表单验证
问题描述
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:""
}
]
}
是否也可以至少验证资历/资源说明(或充其量是技能)?
解决方案
在您的控制器中,您可以定义一个新方法,该方法将根据特定字段及其祖先索引检查特定字段的有效性。以下是技能领域的示例:
component.ts
isSkillValid(resourceDTOSIndex: number, skillIndex: number): boolean {
const resourceDTOSGroup = this.myForm.controls.resourceDTOS as FormGroup;
const skillDTOSGroup = resourceDTOSGroup.controls[resourceDTOSIndex] as FormGroup;
const skillDTOS = skillDTOSGroup.controls.skillDTOS as FormGroup;
return skillDTOS.controls[skillIndex].valid;
};
component.html
<input
formControlName="skill"
class="form-control"
style="margin-right:5px;"
type="text"
placeholder="Enter skill"
id="skill"
name="skill"
aria-label="button1"
aria-describedby="button1"
/>
<div *ngIf="!isSkillValid(i, j)">
The skill field has no valid value
</div>
附言
我真的建议您重构组件并将其拆分为更小的部分,因为它已经很难阅读和操作它。
推荐阅读
- javascript - 递归调用对象方法
- php - file_get_contents 未能打开流 HTTP 请求失败?
- spring - Spring Boot 反应式(webflux)监控与监控普通 Spring Boot MVC 有什么不同吗?
- javascript - 如何通过函数参数发送 POST 数据?
- excel - EXCEL 公式 - 索引匹配、大型和多个标准
- pandas - 如何根据循环的值添加数据框列
- dart - 如何实现一个在mixin上使用的类?
- logging - 格式化 loki 日志流 - 错误:loghttp.PushRequest.Streams
- cordova - 如何在生产中使用 socketio 和 cordova 混合应用程序?
- ios - 苹果证书吊销