Multiple dynamic components using directive — *ngFor | Angular

Oleh Teslenko
3 min readApr 10, 2022

--

I would like to show you the features that can help to create dynamic components in Angular. Of course, there are many articles about creating dynamic components in Angular, and most of them describe the simplest pattern from the documentation.

However, the purpose of this article is to show how to create multiple identical dynamic components with different inputs using *ngFor .

This is an example of a simple single dynamic component.

main.component.ts
main.component.html

But when the goal is to create several identical components with different data, some questions may arise. If we only add *ngFor to our main.component.html and run app, we received an error.

main.component.html

First of all, we need to change @ViewChild => @ViewChildren and type of variable ViewContainerRef => QueryList<ViewContainerRef>. Thus, after loading the page, we will have an array of elements that have the tag #dynamic.

main.component.ts

Next, we need to iterate the array with our html elements and create for each dynamic component.

main.component.ts

I used an array with static data that is passed to each component. Full code example below.

output result
main.component.ts

This way I used one component to create multiple dynamic components but with different input parameters.

Thanks for reading. if you like this article, please 👏 or write a comment. P.S. Please note that in Angular, the creation of dynamic components has been simplified, so even in older version ( to v13) your syntax will be slightly different.

--

--