rish rish - 2 months ago 29
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

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

</div>