How do you dynamically load components in Angular?
- Authors
- Name
- Angular
How Do You Dynamically Load Components in Angular?
In Angular, things are usually simple: components are loaded either through routing, or you place them directly in the template. But what if you need to load a component dynamically - when the user clicks a button or data comes from the server? Don't worry, Angular has tools that allow you to do this on the fly.
Let’s dive into the details.
Why it needs dynamically load components at all?
- Want to show different components depending on user actions? Here it is!
- Need to load parts of the interface only when they are actually needed? Perfect for performance.
- Building dynamic interfaces like modals, widgets or dashboards? There's no way around it.
✅ There Are Steps to Dynamically Load Components in Angular
1. Prepare the Component
Make sure you have a component you want to load.
@Component({
selector: 'app-dynamic-example',
template: `<p>This is a dynamically loaded component!</p>`,
})
export class DynamicExampleComponent {}
2. Create a Placeholder in the Template
Use the ng-template
directive to specify where the dynamic component should be loaded.
<ng-template #container></ng-template>
ViewContainerRef
and ComponentRef
in the Component Class
3. Use Inject ViewContainerRef
into your component and use it to dynamically create components at runtime.
@ViewChild('container', { read: ViewContainerRef, static: true })
container!: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) {} // Use before Angular 13
loadComponent() {
// 1. Get the factory for the component
const factory = this.resolver.resolveComponentFactory(MyDynamicComponent);
// 2. Create the component in the view container
this.container.clear(); // Clear any existing components
// 3. Create the dynamic component
const componentRef = this.container.createComponent(factory);
}
✅ In Angular 13+, it is possible to simplify without ComponentFactoryResolver:
loadComponent() {
this.container.clear();
const componentRef = this.container.createComponent(DynamicExampleComponent);
}
✅ Dynamic Loading with Lazy Modules (Advanced)
You can dynamically lazy load components from a separate module using loadComponent (Angular 14+):
loadComponent() {
import('./dynamic-example/dynamic-example.component').then(({ DynamicExampleComponent }) => {
this.container.createComponent(DynamicExampleComponent);
});
}
✅ Let's Wrap Up
Want your interface to be flexible, fast and smart? Dynamic loading of components is your friend.