Dynamic Components

Dynamic Components

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!


The ViewContainerRef

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.

Anchor Point Example:

<!-- This acts as a marker. The dynamic component will be inserted right here! -->
<ng-template #dynamicContainer></ng-template>

Creating the Component programmatically

Once you have the ViewContainerRef, you can use its createComponent() method.

You simply pass the class name of the component you wish to generate!

Dynamic Generation Example:

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); } }


The *ngComponentOutlet Directive

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!

*ngComponentOutlet Example:

<!-- HTML Template -->
<ng-container *ngComponentOutlet="currentComponent"></ng-container>

<!-- TypeScript --> // currentComponent = AlertComponent;


Exercise 1 of 2

?

Which service is required to programmatically inject a component into an anchor point in the DOM?

Exercise 2 of 2

?

What built-in directive provides a declarative shortcut for rendering dynamic components without writing complex TypeScript logic?