如何将值设置为FormGroup包含Angular中的FormArray

时间:2018-09-14 09:49:11

标签: angular angular-reactive-forms formarray formgroups

如果我有一些数据,则数据结构如下:

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并将这些数据设置为表单?

0 个答案:

没有答案