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

2 Answers 2

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>
4
  • 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
    Commented Oct 4, 2016 at 5: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. Commented Oct 4, 2016 at 5: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
    Commented Oct 4, 2016 at 5: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. Commented Oct 4, 2016 at 5: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:

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.