1

How can I set component's ng-content in js with a new component?

I see that the only view composition mentioned in Angular docs is with routings. But what if I don't want routings in my app?

almog
  • 798
  • 1
  • 7
  • 18

2 Answers2

0

If you want to add from within the component, jnject elementRef: ElementRef in your components constructor and use elementRef.nativeElement.appendChild(someElement). From the outside just use a different method to get hold of the DOM element and add HTML to it.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Can you please elaborate a bit more. Your question doesn't provide much information either. Maybe you're looking for something like http://stackoverflow.com/questions/34636435/angular2-what-is-the-best-way-to-get-a-reference-of-a-template-element (or alternatively `@ContentChild`) – Günter Zöchbauer Jan 07 '16 at 09:13
  • I did what you suggested `elementRef.nativeElement.appendChild(someElement)` It half worked, the DOM got the new selector in it, but the template is not render. How I force the selector rendering? and secondly:Is there a way to insert the component instead of the component's selector? – almog Jan 07 '16 at 13:50
  • I see, you didn't state what you want to add to the DOM. My approach only works with plain HTML. If you want to add Angular2 components dynamically you need to use DCL. – Günter Zöchbauer Jan 08 '16 at 09:32
0

I tried a different approach and succeeded, I used DynamicComponentLoader to load my component to an element selector .

 DynamicComponentLoader.loadAsRoot(Component1, '#div1, injector);

this method load Component1 to an element with id=div1. DynamicComponentLoader is very imported service that should be in every ng2 book.

almog
  • 798
  • 1
  • 7
  • 18