将Angular 2反应形式数据绑定到json数据

时间:2017-01-11 18:44:57

标签: rest angular formbuilder

我正在使用角度2数据驱动(反应)形式。我试图找到一种更好的方法将json数据从休息调用映射到我的表单构建器表单。目前,我正在做类似以下的事情:

this.courseForm = this.fb.group({
    "Title": this.Title,
    "Author": this.Author
});

this.courseService.getCourse(id).then((course) => {
    this.courseForm.controls.Title.setValue(course.Title);
    this.courseForm.controls.Author.setValue(course.Author);
})

<input type="text" formControlName="Title" />
<input type="text" formControlName="Author" />

它可以工作,但是我需要将每个控件分别映射到json对象的每个属性。使用模板驱动表单,我只需要执行以下操作:

course: any[];

this.courseService.getCourse(id).then((course) => {
    this.course = course;
})

<input type="text" [(ngModel)]="course.Title" />
<input type="text" [(ngModel)]="course.Author" />

在将数据驱动表单绑定到json对象时,不确定我是否遗漏了一些简单的内容。

1 个答案:

答案 0 :(得分:0)

dustmouse在评论中提供答案。我的json和form模式是相同的,所以我只需要将以下内容映射到整个json对象:

this.courseForm.setValue(course, {selfOnly: true });

一块蛋糕。谢谢dustmouse!