Dynamic component rendering in Angular 5 with NgComponentOutlet

Matt Blum
Matt Blum
Apr 3, 2018 · 2 min read

Sometimes you have a situation in an application where you don’t actually know what component you want to render at runtime. As an example, let’s think of a checkout process where the selections determine which tabs show up. If the order is free, then it’s just the user information and confirmation tabs that show up. If the order is paid, it’s those plus the payment form.

In this hypothetical, we need to find a way to tell Angular to render whichever components we need. Meet NgComponentOutlet. I didn’t know about this directive and so I proposed a slightly more manual solution but Rob Wormald, God of Angular and other things, pointed me to an even cleaner solution.

Let’s look at some pseudocode that will assist us in visualizing this:

public dynamicTabs = [
{
label: 'User Information',
component: UserInformationComponent
},
{
label: 'Payment',
component: PaymentComponent
},
{
label: 'Thank You',
component: ThankYouComponent
}
];

Each object has a label and a component that we want to render. Now lets assume we want to render these components in a simple tab setup:

<mat-tab-group>
<mat-tab *ngFor="let tab of dynamicTabs" label="{{tab.label}}">
<ng-container *ngComponentOutlet="tab.component">
</ng-container>
</mat-tab>
</mat-tab-group>

And that’s it! Each of those containers will render whichever component you specified in your object. If you need more control than that, you can even pass additional options and custom injectors. All of the inner workings are laid out in the Angular Documentation.

I’m constantly amazed at all of the stuff that Angular can do. In exchanged for some additional complexity compared to React or Vue, you really get a toolbox that is both wide and deep.

Matt Blum

Written by

Matt Blum

I am a full-stack developer and photographer. I love projects in all their forms. Building and creating makes me happy.