rish rish - 1 year ago 271
Javascript Question

Add Dynamic Attributes in Angular2

I have existing javascript function which is used to create dynamic element using setAttribute function. Now I want to append attributes [(ngModel)] into this element for two way data binding. I tried to add this using

obj.setAttribute("[(ngModel)]", "modelName")

But I'm getting error-

Failed to execute 'setAttribute' on 'Element': '[(ngModel)]' is not a valid

Answer Source

Instead of setting attribute from JavaScript, put all the properties inside array and loop it to render all the input fields.

<div ngFor="item in items">

  <input [(ngModel)]="item.modelName" class="form-control" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download