← Back to Angular, page 3

angular-0042 · Hard senior

How do you create components dynamically in Angular using ViewContainerRef, NgComponentOutlet, and the createComponent bindings?

Use ViewContainerRef.createComponent to insert a component at runtime and set its inputs with ref.setInput, or use NgComponentOutlet in a template for simpler cases. The standalone createComponent function with an EnvironmentInjector creates components outside any container, and Angular 20 adds inputBinding, outputBinding and twoWayBinding helpers to wire them up.

Full answer

Sometimes the component type is not known at build time: a dashboard of user-chosen widgets, a modal service, a plugin screen, a toast. Angular offers three tools.

  1. NgComponentOutlet in a template: <ng-container [ngComponentOutlet]="widget()" [ngComponentOutletInputs]="{ title: 'Marks' }" />. This is the easiest option when the template can decide. It supports inputs and a custom injector, and handles destroy for you.

  2. ViewContainerRef.createComponent(Type): gives a ComponentRef. Get a container with viewChild('host', { read: ViewContainerRef }) on an ng-container or div. Then:

    • ref.setInput('message', 'Saved') sets inputs (works with signal inputs, and triggers OnPush updates).
    • ref.instance.closed.subscribe(...) listens to an output().
    • ref.destroy() removes it. Destroying the container, or its host component, also destroys the children.
  3. The standalone createComponent(Type, { environmentInjector, hostElement }) plus ApplicationRef.attachView(ref.hostView) creates a component outside any template. This is the approach for overlays that attach to document.body (the CDK Overlay does something similar).

Angular 20 adds declarative bindings: createComponent(Type, { bindings: [inputBinding('title', () => this.title()), outputBinding('closed', () => this.close())] }). These keep inputs reactive to signals, so you do not need to call setInput repeatedly. twoWayBinding is also available.

Lazy loading plus dynamic creation is a common pairing: const { ChartComponent } = await import('./chart.component') before createComponent. The component code is only downloaded when needed.

Points to watch: always destroy what you create (a modal opened 100 times must not leave 100 components), pass an injector when the dynamic component needs parent-scoped services, and prefer @defer or control flow when the set of components is known in advance.

typescript
import { NgComponentOutlet } from '@angular/common';
import {
  Component,
  ComponentRef,
  ViewContainerRef,
  input,
  inputBinding,
  output,
  outputBinding,
  signal,
  viewChild,
} from '@angular/core';

@Component({
  selector: 'app-alert',
  template: `
    <p>{{ message() }} <button (click)="closed.emit()">Close</button></p>
  `,
})
export class AlertComponent {
  message = input.required<string>();
  closed = output<void>();
}

@Component({
  selector: 'app-toast-host',
  imports: [NgComponentOutlet],
  template: `
    <button (click)="show('Saved')">Show with setInput</button>
    <button (click)="showWithBindings()">Show with bindings</button>
    <ng-container #host />

    <ng-container
      [ngComponentOutlet]="alertType"
      [ngComponentOutletInputs]="{ message: 'Static outlet' }"
    />
  `,
})
export class ToastHostComponent {
  readonly alertType = AlertComponent;
  private readonly host = viewChild.required('host', { read: ViewContainerRef });
  private readonly text = signal('Reactive text');

  show(message: string): void {
    const ref: ComponentRef<AlertComponent> = this.host().createComponent(AlertComponent);
    ref.setInput('message', message);
    ref.instance.closed.subscribe(() => ref.destroy());
  }

  showWithBindings(): void {
    const ref: ComponentRef<AlertComponent> = this.host().createComponent(AlertComponent, {
      bindings: [
        inputBinding('message', this.text),
        outputBinding('closed', () => ref.destroy()),
      ],
    });
  }
}

Angular 20.3, strict template check passes. `inputBinding` and `outputBinding` were added in Angular 20.0.

Key points

  • `NgComponentOutlet` for template-driven cases; `ViewContainerRef.createComponent` for code-driven ones.
  • `setInput` keeps signal inputs and OnPush working. Outputs are listened to through `instance`.
  • Standalone `createComponent` plus `ApplicationRef.attachView` supports overlays.
  • Angular 20 `inputBinding` and `outputBinding` make dynamic wiring declarative.

Common mistakes

  • Assigning `ref.instance.message = ...` for a signal input. It is read-only. Use `setInput`.
  • Forgetting to destroy dynamic components, leaking memory and DOM nodes.
  • Reaching for dynamic creation when `@switch` with fixed components would be simpler.

Follow-ups

  • How do you pass a custom injector to a dynamic component?
  • How would you build a simple modal service?
  • How does lazy loading combine with dynamic creation?

Tips

  • Start with the three tools and when each fits. This shows judgement.
  • Mention cleanup before the interviewer asks.
  • Say that known component sets should use `@switch` or `@defer`, and dynamic creation is for open-ended cases.

Evaluation rubric

  • Names several creation approaches with trade-offs.
  • Uses setInput and handles outputs and cleanup.
  • Knows the newer binding helpers.