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

  1. Page loads faster
  2. Heavy components load only when required
  3. Unnecessary data is not loaded
  4. 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

  1. ViewChild is used to access the container
  2. ViewContainerRef gives control to create components
  3. Dynamic import() returns a promise, so function must be async
  4. createComponent() loads the component
  5. clear() removes old component before loading new one