In Angular, we can load components dynamically on Demand basis or runtime. this will improve application performance. Instead of loading all components upfront, we can load only the required components when needed.
One common way to dynamically load components is by using the ComponentFactoryResolver service. This service allows us to create a factory for a component, which can then be used to instantiate the component dynamically at runtime.
To implement dynamic component loading, we can first create a host element in the template where the component will be rendered. Then, we can use the ComponentFactoryResolver service to create a factory for the desired component.
We can use the factory to create an instance of the component and attach it to the host element.This approach helps to reduce the initial bundle size by loading only the required components at runtime. It can also improve the user experience by reducing the initial load time of the application.
In some cases you may want to create components dynamically at runtime, rather than including them in your template statically. For example, if you're creating a modal dialog that needs to be displayed on demand, you might want to create the dialog component programmatically instead of including it in the template directly.
let's get into action......
- In Our Home Component first, create the host element in the template.
<div #container></div>
<button (click)="loadComponent()">Load Component</button>
- Then, in the component class, inject the ComponentFactoryResolver service and create a reference to the host element:
import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { PopupComponent } from './popup.component';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) { }
loadComponent() {
// Create a factory for the PopupComponent
const factory = this.resolver.resolveComponentFactory(PopupComponent);
// Create an instance of the PopupComponent
const componentRef = this.container.createComponent(factory);
}
}
- then create PopupComponent
import { Component } from '@angular/core';
@Component({
selector: 'app-popup',
template: '<div>Popup Component</div>',
})
export class PopupComponent {}
When the "Load Component" button is clicked, the loadComponent() method is called. This method uses the ComponentFactoryResolver service to create a factory for the PopupComponent. It then uses the factory to create an instance of the component and attach it to the host element (container). This will render the PopupComponent in the DOM.
finally the Popup component is loaded after click event in Home component.
I hope you find this post helpful. Thanks for reading.
Top comments (0)