尝试Diff

时间:2017-08-23 00:08:47

标签: angular typescript angular-reactive-forms

我有一个表单,我试图动态添加控件以使用reactiveForms。

在我的代码中,我正在尝试填充下拉菜单。我正在使用formArray,因为这些是动态字段。

数据:

{ "ruleName": "", "ruleDescription": "", "ruleOutcome": "", "addVariable": "2", "variables": [ { "id": "2", "name": "Device Trust Score", "operator": [ { "name": "Greater Than <", "id": 3 }, { "name": "Less Than >", "id": 4 } ], "values": "" } ] }

HTML:

<tbody formArrayName="variables">
   <tr *ngFor="let variable of addRuleForm.get('variables').controls; let i=index" [formGroup]="variable">
   <td>{{ addRuleForm.controls.variables.controls[i].controls.name.value}}
      <input type="hidden" formControlName="id" value="addRuleForm.controls.variables.controls[i].controls.id.value" [attr.id]="'id'+i">
   </td>
   <td>
      <select class="form-control input-sm" formControlName="operator" [attr.id]="'operator'+i">
         <option value="">Select an Operator</option>
         <option *ngFor="let o of addRuleForm.controls.variables.controls[i].controls.operator.value" value="{{ o.id }}">{{ o.name }}</option>
      </select>
   </td>
   <td>
      <button type="button" class="btn btn-danger btn-sm" (click)="removeVariable(v.id)"><i class="fa fa-trash-o"></i>
      </button>
   </td>
   </tr>
</tbody>

此选择输入会很好地呈现给页面。我检查源并看到该值也已正确设置为ID。

但是,只要我从中选择一个选项,我就会收到此错误:

Error: Error trying to diff '4'. Only arrays and iterables are allowed引用我选择的项目的ID。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

该消息可能会告诉您,您正试图*ngFor某些不理解的内容。

我认为addRuleForm.controls.variables.controls[i].controls.operator.value可能是4?您的意思是在这里使用value属性吗?

如果要遍历JSON对象,可以使用Object.keys。这里有几个例子:access key and value of object using *ngFor