如何用angular2反应形式创建组合对象?

时间:2017-04-12 19:40:08

标签: angular angular2-forms

我有以下两个课程:

export class Machine {
   name = '';
   computer = new Computer()
}

export class Computer {
   os = '';
}

然后在我的组件上使用反应形式我有:

ngOnInit()  {  this.form = this.fb.group(new Machine())  }

并在我的模板中:

 <input class="form-control" formControlName="name"> // the name works fine
 <input class="form-control" formControlName="computer.os">

并在控制台中我收到此错误:

  

找不到具有名称的控件:&#39; computer.os&#39;

是不是可以像这样使用FormBuilder.group?

1 个答案:

答案 0 :(得分:1)

在您拥有等效嵌套属性的情况下(您的表单模型具有带有嵌套'os'属性的'computer'属性),您必须嵌套表单组以达到相同的效果。< / p>

因此,在您的情况下,您需要:

<div [formGroup]="form">
   <input formControlName="name" />
   <div formGroupName="computer">
      <input formControlName="os" />
   </div>
</div>

上面的结构将给出一个form.value:

 {
   name: <value of input field>
   computer: {
      os: <value of second input field>
   }
 } 

我为我的嵌套表单组使用了div,但是你可以使用任何元素(如果你不想改变你的DOM结构,甚至可以使用ng-container)

老实说,我从未见过人们使用实际类来表示其表单模型的示例(我通常会看到接口),但由于formControlName指令基本上使用属性名称,因此它可能仍然有效。

相关问题