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

4

1 回答 1

1

您想要将接口序列化/反序列化为 JSON。Serializr可以做到。

class User {
    @serializable name;
}

class Message {
    @serializable
    author;

    @serializable
    message;
}

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

这是一个更完整的教程

于 2018-09-14T09:59:22.010 回答