Dynamically Instantiate an Angular Component

Share this video with your friends

Send Tweet

In this lesson we learn how to leverage the ComponentFactoryResolver as well as our anchor we defined previously, to dynamically instantiate an Angular component, in our specific case the TabComponent.

We will also learn how to register our dynamic components in the NgModule’s entryComponent property.

Paweł Waszczyński
Paweł Waszczyński
~ 5 years ago

Hi, great course! Got one question: Is there any particular reason why you're using ng-template as ViewContainerRef , and not just regular HTML element like DIV?

Juri Strumpflohner
Juri Strumpflohner(instructor)
~ 5 years ago

Hey. Yes, ng-template allows you to define a piece of HTML, but it is not being rendered actually. The rendering only happens once you pass its reference to some template outlet. A div instead would be immediately be rendered by the browser.

Hope that makes sense.

Paweł Waszczyński
Paweł Waszczyński
~ 5 years ago

Hey. Yes, ng-template allows you to define a piece of HTML, but it is not being rendered actually. The rendering only happens once you pass its reference to some template outlet. A div instead would be immediately be rendered by the browser.

Absolutely, thanks :)

Paweł Waszczyński
Paweł Waszczyński
~ 5 years ago

Ah, sorry, I replied too soon. Ok I understand that app.component HTML has:

    <ng-template let-person="data" #personEdit>
      Hi, I'm {{ person?.name }}.
    </ng-template>

That makes perfect sense. But my question was about

<ng-template dynamicTabAnchor #container></ng-template>

I mean, this ng-template serves as viewContainerRef and is empty at the beginning, so it could be a div. Actually I'm confused why when you add stuff to this ng-template is shows in the browser, because this ng-template it not passed anywhere to outlet?