1

I am using JavaScript API to create html elements from JSON Schema. When I passed the json schema, it's returns widget html element object.

Widget is HTML DOM object which contains tagName, id. So for two data binding I have include [(ngModel)] into dom object, for this I am using-

widget.setAttribute("[(ngModel)]", "model");

But It's giving me error-

[(ngModel)]' is not a valid attribute name

Inside @NgModule, I have already included BrowserModule and FormsModule

deen
  • 2,185
  • 7
  • 29
  • 53
  • Please post some code. To me it's entirely unclear what "I want to apply [(ngModel)] for two way data binding using setAttribute() function" could mean. You probably need to add `BrowserModule`, (or `CommonModule`) and `FormsModule` to `imports` of your current module. – Günter Zöchbauer Oct 18 '16 at 05:15
  • @GünterZöchbauer thnx for reply, I have update question – deen Oct 18 '16 at 05:29

1 Answers1

1

Angular bindings and component/directive instantiation is only happening for markup added statically to a components template. [] or () are never added to the DOM by Angular2 and Angular2 doesn't care about these being added to the DOM by other means. Bindings are processed by Angular before it adds HTML to the DOM

There is a way to add/remove components dynamically to the DOM using ViewContainerRef.createComponent() but that's it. (for an example see Angular 2 dynamic tabs with user-click chosen components)

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • So whatever javascript API I am using which returns the DOM objects, it won't work for binding? – deen Oct 18 '16 at 07:37
  • Exactly. You can't add/remove binding dynamically. A workaround could be to create components at runtime and add such a component. Components created at runtime can introduce new bindings. See for example http://stackoverflow.com/questions/40060498/angular-2-1-0-create-child-component-on-the-fly-dynamically/40080290#40080290 – Günter Zöchbauer Oct 18 '16 at 07:43
  • One more question, Can I get the DOM object reference from code example which you have shared? – deen Oct 18 '16 at 09:57
  • Sorry, I don't understand what "DOM object reference" you mean. – Günter Zöchbauer Oct 18 '16 at 10:03
  • example which you have shared, Inside that there is variable called html, I guise which takes the html string element, right?. Now I want the DOM object of this html string – deen Oct 18 '16 at 10:06
  • Not sure what you try to accomplish. If the dynamically component contains `constructor(public elRef:ElementRef) {}` then you can access the DOM element using `this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []); this.cmpRef.instance.elRef.nativeElement...` where `nativeElement` is the actual DOM element. – Günter Zöchbauer Oct 18 '16 at 10:11
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/125996/discussion-between-rish-and-gunter-zochbauer). – deen Oct 18 '16 at 10:24