简体   繁体   中英

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

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>

As Günter states above, "In the DOM bindings won't have any effect at all". However this was true of Angular 1 as well. In Angular 1, you always had to $compile your DOM fragment before it would have any effect.

Angular 2's equivalent of $compile is a bit different, but it may help you to research along those lines. For example:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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