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

问题描述 投票:1回答:1

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

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

angular angular-reactive-forms formarray formgroups
1个回答
1
投票

您希望将接口序列化/反序列化为JSON。 Serializr可以做到这一点。

class User {
    @serializable name;
}

class Message {
    @serializable
    author;

    @serializable
    message;
}

deserialize(Message, {
    "message": "test",
    "author": 123
});

这是一个更多的throughout tutorial

© www.soinside.com 2019 - 2024. All rights reserved.