5

I am playing around with Renderer2 and ViewContainerRef in Angular 6. I wanted to dynamically render a new component to a div that was rendered by Renderer2.

So basically, this is how i want it to happen.

const el = this.renderer.createElement('div');
this.viewContainerRef: ViewContainerRef = el;
const factory = this.factoryResolver.resolveComponentFactory(element.elementComponentType);
const componentRef = this.viewContainerRef.createComponent(factory);

and here is how the rendered HTML should look like

<div> <--- This will be the viewContainerRef
    <app-component></app-component> <--- this is the dynamic Component that I want to render
</div>

— Update —

Already found the answer to my prayers, thanks to Max.

Link : https://stackoverflow.com/a/44853707

It turns out that didn’t need a new view viewContainerRef to display a factory.

Mods, can close this now or reference this to the link i mentioned above.

6
  • But you do need to append this dynamically created Div to the view/body before you add dynamic components to it. Commented Jan 8, 2019 at 16:50
  • @nicraft Yeah i already did that, but how do i use that dynamically creted div? One that i could think of was assign a anchor name but that’s not possible for a dynamic element afaik Commented Jan 8, 2019 at 22:18
  • I don't think it's possible. ViewContainers are defined during compilation. Why do you need to dynamically create view container? Commented Jan 9, 2019 at 13:03
  • 1
    @MaxKoretskyiakaWizard i found the answer and it was your answer from another question before. stackoverflow.com/a/44853707 Commented Jan 10, 2019 at 6:04
  • 3
    I would prefer the approach of using ` @ViewChild('element', {read: ViewContainerRef}) private anchor: ViewContainerRef;` in stead of modifying DOM outside the angular. as shown here: stackoverflow.com/a/53191913/9386929 Commented Jan 10, 2019 at 14:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.