首先,我只是从 Angular 2 开始,我正在尝试构建一个嵌套表单并对其进行验证,并将新的对象项目添加到对象 GroupProject 中。
这是我的 ts 文件的一部分:
ngOnInit() {
this.myForm = this.formBuilder.group({
groupproject: this.formBuilder.array([
this.initGroupProjects()
])
});
}
public initGroupProjects(): any {
return this.formBuilder.group({
groupproject: this.formBuilder.array([this.initProjects()])
});
}
public initProjects(): any {
return this.formBuilder.group({
name: ['', [Validators.required, Validators.minLength(3)]],
some_array: this.formBuilder.array([
this.formBuilder.group({
name: ['', Validators.required],
attr: ['', Validators.required],
some_id: [1, Validators.required]
})
])
});
}
addProject(): void {
const control = < FormArray > this.myForm.controls['projects'];
control.push(this.initProjects());
}
看法:
<form [formGroup]="myForm" novalidate (ngSubmit)="onSubmit(myForm)">
<div formArrayName="groupproject">
<div [formGroupName]="gp" *ngFor="let objGroupProject of myForm.controls.groupproject.controls; let gp = index">
<div formArrayName="projects">
<div [formGroupName]="i" *ngFor="let project of objGroupProject.controls.projects.controls; let i = index">
<md-input placeholder="Name" formControlName="name"></md-input>
<div formArrayName="some_array">
<div [formGroupName]="x" *ngFor="let some_obj of project.controls.some_array.controls; let x = index">
<div>
<md-input placeholder="Nome" formControlName="name"></md-input>
<small *ngIf="!some_obj.controls.name.valid">Nome é requerido</small>
</div>
<md-input type="number" placeholder="Cost" formControlName="attr" required></md-input>
</div>
</div>
</div>
</div>
</div>
</div>
<button type="submit" md-raised-button color="primary" [disabled]="!myForm.valid">Submit</button>
</form>
<pre>form value: <br>{{myForm.value | json}}</pre>
表单值的输出:
表单值:
{
"groupproject":[
{
"projects":[
{
"name":"",
"some_array":[
{
"name":"",
"attr":"",
"some_id":1
}
]
},
{
"name":"",
"some_array":[
{
"name":"",
"attr":"",
"some_id":1
}
]
}
]
}
]
}
好吧,如您所见,我有一些称为 groupprojects 的数组,每个数组中有 1 个数组。
所以问题是我无法在对象 groupproject 中插入对象项目
实际上我收到以下错误:
错误类型错误:无法读取未定义的属性“控件”