0

I have a form that I am trying to dynamically add controls to using reactiveForms.

Within my code, I am trying to populate a dropdown menu. I am using formArray since these are dynamic fields. The

Data:

{ "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>

This select input gets rendered to the page just fine. I inspect the source and see that the value has also been set to the ID correctly.

However, as soon as I select an option from it, I get this error:

Error: Error trying to diff '4'. Only arrays and iterables are allowed referencing the ID of the item I selected.

Any thoughts?

SBB
  • 8,560
  • 30
  • 108
  • 223

1 Answers1

1

That message may be telling you that you are trying to *ngFor something that it does not understand.

I assume this addRuleForm.controls.variables.controls[i].controls.operator.value might be 4? Did you mean to use the value property here?

If you want to iterate through a JSON object, you can use Object.keys. There are several examples here: access key and value of object using *ngFor

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • that line you pasted returns the following: `[ { "name": "In List", "id": 1 }, { "name": "Not In List", "id": 2 } ]`. That is what my `*ngFor` is trying to iterate – SBB Aug 23 '17 at 00:31
  • That's the problem then. *ngFor can only iterate arrays and iterables, not JSON objects. – DeborahK Aug 23 '17 at 00:34