Angular 2 使用 FormBuilder 访问 FormArrays 中的嵌套 FormArrays



首先,我只是从 Angular 2 开始,我正在尝试构建一个嵌套表单并对其进行验证,并将新的对象 Projects 添加到对象 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 个数组。

所以问题是我无法在对象组项目中插入对象项目

实际上我收到以下错误:

错误类型错误: 无法读取未定义的属性"控件">

很可能您在以下代码中有一个类型:

public initGroupProjects(): any {
return this.formBuilder.group({
groupproject: this.formBuilder.array([this.initProjects()])
^^^^^^^
});
}

我认为它应该是projects而不是groupproject

public initGroupProjects(): any {
return this.formBuilder.group({
projects: this.formBuilder.array([this.initProjects()])
});
}

还检查工作Plunker 示例

参见

  • Angular 2 反应式形式的嵌套数组?

相关内容

  • 没有找到相关文章

最新更新