Dynamic Component Loading
Dynamic loading means loading a component only when needed, not on page load.
When a page has a lot of data, loading everything at once is not required.
Extra information can be loaded on button click.
Why Dynamic Component Loading is Used
- Page loads faster
- Heavy components load only when required
- Unnecessary data is not loaded
- Better performance
Example:
User page shows basic info first.
Extra user details load only when button is clicked.
Create Component
ng g c user-details
User Details Component (user-details.ts)
import { Component } from '@angular/core';
@Component({
selector: 'app-user-details',
standalone: true,
template: `<h1>User All Details</h1>`
})
export class UserDetails {}
App HTML (app.html)
<button (click)="loadUserDetails()">
Load User Details
</button>
<ng-container #container></ng-container>
ng-container is used as a container to load components dynamically.
App Component (app.ts)
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-root',
standalone: true,
templateUrl: './app.html'
})
export class App {
@ViewChild('container', { read: ViewContainerRef })
container!: ViewContainerRef;
async loadUserDetails() {
this.container.clear();
const userDetail =
await import('./user-details/user-details');
this.container.createComponent(userDetail.UserDetails);
}
}
Important Points
ViewChildis used to access the containerViewContainerRefgives control to create components- Dynamic
import()returns a promise, so function must beasync createComponent()loads the componentclear()removes old component before loading new one