Create Angular Components Dynamically at runtime
Nhan Nguyen
Posted on August 23, 2024
Dynamically create and destroy components
We need two things.
- Some components.
- Some certain ViewContainer will be used to create this component.
The first part is just a class constructor of the component we want to create.
The ViewComtainer is more complex. Think of it as some box or container that can be created next to any DOM element in the template, and inside this container, we just put different views that must be rendered on the page. We can create our containers or reuse the ones Angular created automatically.
Each Angular component has its own ViewContainer. We can access this ViewContainer by injecting the ViewContainer using dependency injection. This ViewContainerRef provides various APIs to manipulate the views inside the container, such as createComponent.
It appears after viewing the AppComponent and not inside it.
If we want to specify explicitly the location in the template where this new component has to be created, we need to make our own ViewContainer.
To do this, we need an element that will act as an anchor; this can be any DOM element, or we can use ng-container construct and declare a template variable that will be used inside the viewChild function as an argument.
We can use the clear API that *ViewContainerRef * provides. This API allows us to remove everything from the particular ViewContainer.
We can also remove a specific view from the ViewContainer by using the remove method. And there, we can provide the index of the view that has to be removed.
Update component inputs
We can use the setInput method that ComponentRef provides.
We have to provide two arguments. The first is a string that represents the name of the input, and the second is the value of this input.
React to component output
We need to access the component instance and the emitter property; from there, we can subscribe to it and provide a callback function that will be executed when the event is emitted.
Demo
A complete example is here π https://stackblitz.com/edit/stackblitz-starters-ugeydc?file=src%2Fmain.ts
I hope you found it helpful. Thanks for reading. π
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Posted on August 23, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.