Load Dynamic Components in Angular
In Angular, a dynamic component refers to a component that is created at runtime, rather than being defined in the component template at compile time. Dynamic components are often used when the number or type of components that need to be rendered is not known ahead of time, or when components need to be created based on user interaction or data from an external source.
To create a dynamic component in Angular, you need to use the ComponentFactoryResolver class. This class provides a createComponent() method that allows you to dynamically create a component instance.
Here’s an example of how to create a dynamic component in Angular:
1. To render a dynamic component, you first need to create a component where the dynamic component will be rendered. In this example, I create a Colors
component using the command below:
ng g component Colors
2. After that you must first create the components you want to render. In this example, I create two components, Red
and Green
component using the following commands.
ng g component red
ng g component green
3. Copy the code below and paste it inside a file named colors.component.html
:
<div class="container text-center">
<h2>Dynamic Component</h2>
<button class="btn btn-danger m-3" (click)="buttonClick('red')">Red</button>
<button class="btn btn-success m-3" (click)="buttonClick('green')">Green</button>
<div class="card m-3">
<div class="card-body">
<p>Dynamic components will load here...</p>
<ng-container #container>
</ng-container>
</div>
</div>
</div>
In the above code, I added two buttons with different colors, and when the user clicks a button, I pass the button’s color as an event parameter.
<ng-container #container></ng-container>
refers to a container element with the ID 'container'. We will use this container to render our dynamic components.
4. Copy the code snippet below and paste it into the file named colors.component.ts
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { RedComponent } from '../red/red.component';
import { BlackComponent } from '../black/black.component';
@Component({
selector: 'app-colors',
templateUrl: './colors.component.html',
styleUrls: ['./colors.component.css'],
})
export class ColorsComponent {
@ViewChild('container', {read: ViewContainerRef, static: true}) container!: ViewContainerRef;
constructor() {}
ngOnInit() {}
buttonClick(component: string) {
this.container.clear();
let dynamicComponent = this.getComponent(component);
if (dynamicComponent) {
this.container.createComponent(dynamicComponent);
}
}
getComponent(componentName: string) {
switch (componentName) {
case 'red':
return RedComponent;
case 'green':
return GreenComponent;
default:
return;
}
}
}
This line of code declares a property called container
using the @ViewChild
decorator.
The first argument of @ViewChild
is the name of the element or directive that we want to access. In this case, the string 'container'
, refers to an element with the ID 'container' in the template.
The second argument is an options object that specifies how to read the element or directive. In this case, we want to read it as a ViewContainerRef
object, which allows us to dynamically add or remove components to the container.
Finally, the static
option is set to true
, which means that the container
property will be available as soon as the component is created.
Overall, @ViewChild(‘container’, {read: ViewContainerRef, static: true}) container!: ViewContainerRef
line sets up a reference to the container element with ID ‘container’, and provides access to the ViewContainerRef
API, allowing us to dynamically add or remove components to the container.
When the button is clicked, we obtain a reference to a component using the getComponent
method. We then pass that reference to the createComponent
method of container reference.
clear()
method
When adding a dynamic component, it is added on top of any previously added components in the container. This can result in multiple components being displayed at the same time. To avoid this, it is important to clear the container before adding a new component.
The clear()
method is called on a ViewContainerRef
object, which is a reference to the container where the dynamic components are rendered. By calling clear()
on this object, any previously added components are removed from the container.
Overall, this.container.clear()
ensures that only one dynamic component is displayed at a time, by clearing the container before adding a new component.