Angular’s dynamic component loader is a feature that allows components to be loaded dynamically at runtime, enabling more flexibility and dynamism in Angular applications. It enables developers to load components dynamically based on certain conditions or user interactions, enhancing the application’s responsiveness and usability.
A Step-by-Step Guide to Angular (17+) Dynamic Component Loader
In this guide, I’ll demonstrate how to dynamically load two components: “Book” and “Magazine”. We’ll utilize navigation buttons for easy switching between them.
Create a new Angular project
ng new dynamic-components
Edit app.component.html
Use the ngComponentOutlet
directive to load dynamic components. Each dynamic component object has a component and inputs properties.
<div>
<h1>{{ title }}</h1>
<ng-container
*ngComponentOutlet="
dynamicComponent.component;
inputs: dynamicComponent.inputs
"
/>
<button (click)="displayComponent(false)">Prev</button>
<button (click)="displayComponent(true)">Next</button>
<hr />
<div>Dynamic component no. {{ currentIndex }}</div>
<router-outlet />
</div>
Edit app.component.ts
import { NgComponentOutlet } from '@angular/common';
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { DynamicComponent, DynamicComponentsService } from './service/dynamic-components.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [NgComponentOutlet, RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent {
title = 'Dynamic Components Demo';
currentIndex = 0;
componentsList!: DynamicComponent;
constructor(private dc: DynamicComponentsService) {
this.componentsList = dc.getDCs();
}
get dynamicComponent() {
return this.componentsList[this.currentIndex];
}
displayComponent(next: boolean) {
next ? this.currentIndex++ : this.currentIndex--;
const dcs = this.componentsList.length - 1;
// Reset the current index back to 0 when we reach the end of an array.
if (this.currentIndex > dcs) {
this.currentIndex = 0;
}
// Assign the end of an array when we reach 0.
if (this.currentIndex < 0) {
this.currentIndex = dcs;
}
}
}
Create a service
ng g s service/dynamic-components
Edit dynamic-components.service.ts
Create a list of dynamic components. We will use two components (Book and Magazine).
import { Injectable, Type } from '@angular/core';
import { MagazineComponent } from '../components/magazine/magazine.component';
import { BookComponent } from '../components/book/book.component';
export type DynamicComponent = { component: Type<MagazineComponent | BookComponent>, inputs: Record<string, string> }[];
@Injectable({
providedIn: 'root'
})
export class DynamicComponentsService {
constructor() { }
getDCs() {
return [
{
component: MagazineComponent,
inputs: { headline: 'Dolor sit amet consectetur adipisicing elit',
perex: 'Ab molestiae, sequi tenetur laudantium natus qui fugiat recusandae incidunt fugit quaerat repudiandae labore, rem placeat, iure magni asperiores nisi dolores delectus expedita ut.' },
},
{
component: BookComponent,
inputs: {
title: 'Facere quos veritatis ',
overview: 'Facere quos veritatis adipisci placeat, corporis fuga ratione alias architecto.Quia, autem.Amet a nemo in officiis saepe ullam hic, reprehenderit labore repudiandae numquam animi neque placeat dolore aliquam illum ut, adipisci velit'
},
},
{
component: MagazineComponent,
inputs: {
headline: 'Culpa at voluptatem molestias dolorum reprehenderit',
perex: 'veritatis corporis autem quia modi odio eum? Accusantium itaque voluptate a enim! Explicabo tempora molestias consectetur molestiae perferendis reprehenderit nesciunt officiis numquam consequuntur, quaerat, culpa tenetur error distinctio.'
},
},
{
component: BookComponent,
inputs: {
title: 'Obcaecati eveniet voluptatibus impedit',
overview: 'obcaecati eveniet voluptatibus impedit nemo eligendi optio? Ut officiis magni veniam vitae laborum debitis doloribus repudiandae voluptatibus rerum aliquam, eveniet dolores non ab id enim quae eius nam nobis molestiae eligendi beatae aliquid? Voluptatem ad autem odio.'
},
}
] as DynamicComponent;
}
}
Create a component book
ng g c components/book
Edit book.component.html
<h2>Book</h2>
<div>
<h4>{{ title }}</h4>
<p>{{ overview }}</p>
</div>
Edit book.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-book',
standalone: true,
imports: [],
templateUrl: './book.component.html',
styleUrl: './book.component.scss'
})
export class BookComponent {
@Input() title!: string;
@Input() overview!: string;
}
Create a component magazine
ng g c components/magazine
Edit magazine.component.html
<h2>Magazine</h2>
<div>
<h4>{{ headline }}</h4>
<p>{{ perex }}</p>
</div>
Edit magazine.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-magazine',
standalone: true,
imports: [],
templateUrl: './magazine.component.html',
styleUrl: './magazine.component.scss'
})
export class MagazineComponent {
@Input() headline!: string;
@Input() perex!: string;
}
For further details, please visit https://angular.io/guide/dynamic-component-loader.