2

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
deen
  • 2,185
  • 7
  • 29
  • 53

2 Answers2

1

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>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • hi, thnx for response, actually I am using metawidget javascript api to generate element from JSON schema. So I went through api where they are using settAtributes to append attributes. – deen Oct 04 '16 at 05:00
  • 2
    Adding any Angular2 specific binding syntax to the DOM is pointless. Angular2 converts these bindings to JS before it adds components to the DOM. In the DOM bindngs won't have any effect at all. – Günter Zöchbauer Oct 04 '16 at 05:14
  • So is it a goodchoice to predefine a template and the use it, istead dynamically append or add an attribute to it? @Günter Zöchbauer – peaceUser Oct 04 '16 at 05:50
  • 3
    Definitely. Try to avoid modifying the DOM imperatively. The preferred way is to only update the model and let `*ngIf`, `*ngFor`, `{{}}`, ..., and custom components and directives that use them, do the DOM updating. – Günter Zöchbauer Oct 04 '16 at 05:53
1

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:

Community
  • 1
  • 1
Richard Kennard
  • 1,325
  • 11
  • 20