简体   繁体   English

如何将动态创建的表单字段绑定到Angular 2中的对象?

[英]How to bind dynamically created form fields to an object in Angular 2?

Using Angular 2 I'm trying to build a generic form for an arbitrary object by dynamically creating input fields for each attribute. 我正在尝试使用Angular 2通过为每个属性动态创建输入字段为任意对象构建通用形式。

Given an object entity I loop through each attribute, using a pipe to get the array of attributes. 给定一个对象entity我使用管道获取属性数组,遍历每个属性。

A field is created for each attribute key which I then want to bind back to the entity . 为每个属性key创建一个字段,然后将其绑定回该entity

Here is the code: 这是代码:

<tr *ngFor="let key of entity | keys">
  <td><label for="{{key.key}}">{{key.key}}</label></td>
  <td><input id="{{key.key}}" type="text" [(ngModel)]="key.value"></td>
</tr>

So the problem is that the fields are bound using [(ngModel)]="key.value" to the keys rather than to entity . 因此,问题在于这些字段是使用[(ngModel)]="key.value"绑定到keys而不是entity

Is there any way to bind the field to the entity instead? 有什么方法可以将字段绑定到entity吗?

Or is there another way to update the values on the entity? 还是有另一种方法来更新实体上的值?

Use an index in ngFor to bind the entity value. ngFor使用index来绑定实体值。

<tr *ngFor="let key of entity | keys;let i = index">
  <td><label for="{{key.key}}">{{key.key}}</label></td>
  <td><input id="{{key.key}}" type="text" [(ngModel)]="entity[i].value"></td>
</tr>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM