Normally, you render components declaratively by placing their HTML tags in your template (e.g., <app-user>).
But what if you don't know which component you need to render until the application is running?
For example, creating a dynamic modal system where the popup content changes entirely based on user clicks!
To dynamically insert a component, you first need an anchor point in the DOM.
You provide this anchor using an <ng-template> tag combined with a template reference variable.
Then, you access that anchor in TypeScript using ViewContainerRef.
<!-- This acts as a marker. The dynamic component will be inserted right here! --> <ng-template #dynamicContainer></ng-template>
Once you have the ViewContainerRef, you can use its createComponent() method.
You simply pass the class name of the component you wish to generate!
import { ViewContainerRef, ViewChild } from '@angular/core';
import { AlertComponent } from './alert.component';
export class MainComponent {
// Grabs the #dynamicContainer from the HTML
@ViewChild('dynamicContainer', { read: ViewContainerRef })
container!: ViewContainerRef;
loadAlert() {
// Clears anything currently in the container
this.container.clear();
// Programmatically generates and inserts the component!
this.container.createComponent(AlertComponent);
}
}
Writing ViewContainerRef logic can sometimes feel tedious.
Angular provides a fantastic shortcut directive called *ngComponentOutlet.
You bind it to a TypeScript variable containing the component class, and Angular handles the generation automatically!
<!-- HTML Template --> <ng-container *ngComponentOutlet="currentComponent"></ng-container><!-- TypeScript --> // currentComponent = AlertComponent;
Which service is required to programmatically inject a component into an anchor point in the DOM?
What built-in directive provides a declarative shortcut for rendering dynamic components without writing complex TypeScript logic?