You are on page 1of 4

Dynamic component loader

Component templates are not always �xed. An application might need

to load new components at runtime. This cookbook shows you how to

add components dynamically.

See the live example / download example of the code in this cookbook.

Rendering components dynamically


The following example shows how to build a dynamic ad banner.

The hero agency is planning an ad campaign with several different ads

cycling through the banner. New ad components are added frequently by

several different teams. This makes it impractical to use a template with

a static component structure.

Instead, you need a way to load a new component without a �xed

reference to the component in the ad banner's template.

The NgComponentOutlet directive can be used to instantiate

components and insert them into the current view. This directive allows

you to provide a component class that should be rendered, as well as

component inputs to be used during initialization.


src/app/ad-banner.component.ts

@Component({
selector: 'app-ad-banner',
standalone: ,
imports: [ , ],
: `
<div class="ad-banner-example">
<h3>Advertisements<∕h3>
<ng-container *ngComponentOutlet="
currentAd.component;
inputs: currentAd.inputs;
" ∕>
<button (click)="displayNextAd()">Next<∕button>
<∕div>
`
})
{
adList = inject( ).getAds();

currentAdIndex = 0;

currentAd() {
.adList[ .currentAdIndex];
}

displayNextAd() {
.currentAdIndex++;
∕∕ Reset the current ad index back to `0` when we
reach the end of an array.
( .currentAdIndex === .adList.length) {
.currentAdIndex = 0;
}
}
}

The AdBannerComponent class injects the AdService service and

requests a list of ads. The "current ad" index is set to 0 initially to

indicate that the �rst ad should be displayed. When a user clicks the
"Next" button, the index is increased by one. Once the index reaches the

length of the ads array, the index is reset back to 0 .

In the template, the currentAd getter is used to retrieve a current ad. If

the value changes, Angular picks it up and re�ects the changes in the UI.

Different components from the


service
Components returned from the AdService service and used in

NgComponentOutlet in the AdBannerComponent template can be

different. Angular detects if a component class has changed and

updates the UI accordingly.

Here are two sample components and the service providing them with

their inputs:

hero-job-ad.component.ts hero-pro�le.component.ts ad.service.ts

{ , } '@angular∕core';

@Component({
standalone: ,
: `
<div class="job-ad">
<h4>{{ headline }}<∕h4>
{{ body }}
<∕div>
`,
})
{
@Input() headline!: ;

@Input() body!: ;
}
Final ad banner
The �nal ad banner looks like this:

You might also like