As a contributor to StackOverflow I see questions related to dynamic components in Angular very frequently. Although the Angular documentation for dynamic components is really good (in my opinion) and covers everything a developer needs to know, it is hard to understand everything in detail, too. Especially for beginners. This is why I decided to write a short article about the easiest possible solution that comes to my mind.
This article is intended to be as minimalistic as possible!
And here we go:
Let’s go through it step by step. At first we create a reference to the container inside of our component class. This is common practice and most of the Angular developers are very likely familiar with it. It happens in line 12. In addition to the template reference we need to inject the
ComponentFactoryResolver. This class provides a function called
resolveComponentFactory which is required to analyse the component source. In the template we also have a button that triggers a function
loadComponent which inserts the component dynamically by executing 3 lines of code:
Clear the container
Create a so called factory object of your components source
Create an instance of the factory object and inject it into the template
(Optional) You can modify public properties or trigger public functions of the dynamically created component by using the componentRef
The use case for dynamic components is very likely covered by structural directives such as *ngFor or *ngIf. The developer should first think about them before going with the dynamic component approach. The reason is that it adds an extra layer of unnecessary complexity. In most of the cases I’ve ever came across, structural directives are absolutely feasible.
What do you think happens if you remove the
viewRef.clear() execution? Please let me know for which use cases you prefer dynamic components over structural directives? Did you face any problem for which structural directives haven’t been feasible?
We, at interfacewerk, prefer simple solutions for complex problems. If you have any kind of problems, please contact us and we will point out a solution.