如果我有一些数据,数据结构如下:
interface IProject {
name: string;
tasks: ITask[];
}
interface ITask {
name: string;
employee: IEmployee[];
}
interface IEmployee {
name: string;
}
现在我有一些这样的项目数据:
project = {
name: 'first project',
tasks: [
{
name: 'task1',
employee: [{name: 'employee1'}, {name: 'employee2'}],
},
{
name: 'task2',
employee: [{name: 'employee2'}, {name: 'employee3'}],
},
],
}
也许这种方式很有用:
ngOnInit() {
this.form = this.fb.group({
name: [this.project.name],
tasks: this.fb.array([]),
});
this.setTasks();
}
setTasks() {
const taskControl = <FormArray>this.form.controls.tasks;
this.project.tasks.forEach(t => {
const taskForm = this.fb.group({
name: [t.name],
exployee: this.fb.array([]),
});
const employeeControl = <FormArray>taskForm.controls.exployee;
t.exployee.forEach(e => {
employeeControl.push(this.fb.group({name: [e.name]}));
}
taskControl.push(employeeControl);
}
}
有没有什么优雅的方法可以用 FormArray 构建一个 FormGroup 并将这些数据设置为表单?