Load components dynamically runtime — Angular

Narendra Singh Rathore
2 min readJul 11, 2022

Yes, we can load components dynamically at runtime but there is a catch we still have to declare them in our declaration array of module. We used this feature in our angular application where we need to show components based on selection in a dialog. For reference image attached below.

So we have a module that display a dialog on click. In dialog we have to show tab/component selection on left and selected one on right.

To achieve this we can use mat-tab from angular material but that doesn’t come with vertical tab menu out of the box we have to do lots of customization to achieve that.

Better solution was to create two section

display: flex, flex-direction: row // default

Then we can use ViewContainerRef to achieve that on click. We have to first declare the components in declaration array of NgModule of our module.

Then we are using a directive that is later on used to get the template reference and embed new components on click. We can also pass data to components loaded dynamically.

Let us see the actual code below:

Directive

Our component that uses the above directive

We have a interface that we are using to give a generic type when loading components and class that take array of object having component and data.

A service that contains array of our components.

And finally our component.ts that uses the directive to get template reference and update the view container on click.

Feel free to get more info from original article from angular.io. Don’t forgot to like and follow.

--

--