Dynamically Creating Components With Angular – NetanelBasal
For the simplicity we are going to use a simple alert component that will take as Input the alert type. Next, If you think about it, eventually components are actually DOM elements so if you need to…
In this article we will learn how to dynamically create components in Angular.
First, we need a component.
the alert type.
Next, If you think about it, eventually components are actually DOM elements so if you need to insert an element, you need a place to “put” it.
In Angular this place is called a container.
element is the place, or in the Angular world, the container.
Note: The container can be any DOM element or component.
decorator that also takes a local variable as parameter.
element ( our container ) and also exposes an API to create components.
method, we need to add one more service.
as an object that knows how to create a component.
method that will be used by the container ( ViewContainerRef ) internally.
Now the final step.
Let’s explain what is happening piece by piece.
Every time we need to create the component we need to remove the previous view, otherwise, it will append more components to the container. (not required if you need multiple components)
method takes a component and returns the recipe for how to create a component.
method from the factory and will append the component as a sibling to our container.
And don’t forget to destroy the component:
The last step is to add your dynamic components to the entryComponents section:
The final code is here.
Follow me on Medium or Twitter to read more about Angular, Vue and JS!