Angular

Dynamic Components in Angular: NgComponentOutlet, createComponent and Lazy Loading

Some screens can't list their components in a template ahead of time: a dashboard where users pick widgets, a page built from a CMS or backend configuration, a plugin area. A long @switch over every possible type works at first, but every new widget means editing that template, and every widget ends up in the same bundle.

Angular has two ways to render a component chosen at runtime. NgComponentOutlet covers most cases from the template, and ViewContainerRef.createComponent() gives full programmatic control. This guide shows both with standalone components, then adds lazy loading so each widget's code downloads only when it's needed. Examples use current Angular APIs (v17+).

The Example: Widgets from Configuration

Suppose the backend returns a layout like this:

TypeScript
type WidgetConfig =
  | { type: 'sales-chart'; inputs: { range: '7d' | '30d' } }
  | { type: 'todo-list'; inputs: { listId: string } };

Each widget is an ordinary standalone component with inputs and outputs:

TypeScript
import { Component, input, output } from '@angular/core';

@Component({
  selector: 'app-todo-list',
  standalone: true,
  template: `
    <h3>Tasks ({{ listId() }})</h3>
    <button (click)="completed.emit(listId())">Mark all done</button>
  `,
})
export class TodoListComponent {
  listId = input.required<string>();
  completed = output<string>();
}

Option 1: NgComponentOutlet in the Template

For "render component X with these inputs", NgComponentOutlet is the simplest tool. Map each config type to a component class and let the outlet do the rest:

TypeScript
import { Component, Type, input } from '@angular/core';
import { NgComponentOutlet } from '@angular/common';
import { SalesChartComponent } from './sales-chart.component';
import { TodoListComponent } from './todo-list.component';

const WIDGETS: Record<WidgetConfig['type'], Type<unknown>> = {
  'sales-chart': SalesChartComponent,
  'todo-list': TodoListComponent,
};

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [NgComponentOutlet],
  template: `
    @for (widget of widgets(); track $index) {
      <ng-container *ngComponentOutlet="registry[widget.type]; inputs: widget.inputs" />
    }
  `,
})
export class DashboardComponent {
  widgets = input.required<WidgetConfig[]>();
  registry = WIDGETS;
}

The inputs option (Angular 16.2+) passes values through Angular's normal input handling, so signal inputs, ngOnChanges and OnPush all behave as they would in a static template. When widget.inputs changes, the outlet updates the existing component instead of recreating it.

The limitation: NgComponentOutlet has no option for outputs. When you need to react to a widget's events, create the component in code.

Option 2: ViewContainerRef.createComponent()

Get a ViewContainerRef for an anchor in the template and create components into it:

TypeScript
import {
  Component, ComponentRef, DestroyRef, OutputRefSubscription,
  ViewContainerRef, effect, inject, input, viewChild,
} from '@angular/core';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  template: `<ng-container #slot />`,
})
export class DashboardComponent {
  widgets = input.required<WidgetConfig[]>();
  private slot = viewChild.required('slot', { read: ViewContainerRef });
  private refs: ComponentRef<unknown>[] = [];
  private subscriptions: OutputRefSubscription[] = [];

  constructor() {
    // Re-render whenever the configuration input changes.
    effect(() => this.render(this.widgets()));
    inject(DestroyRef).onDestroy(() => this.clear());
  }

  private render(configs: WidgetConfig[]) {
    this.clear();
    for (const config of configs) {
      const ref = this.slot().createComponent(WIDGETS[config.type]);

      for (const [name, value] of Object.entries(config.inputs)) {
        ref.setInput(name, value);
      }

      if (ref.instance instanceof TodoListComponent) {
        this.subscriptions.push(
          ref.instance.completed.subscribe(id => console.log('completed', id)),
        );
      }
      this.refs.push(ref);
    }
  }

  private clear() {
    this.subscriptions.forEach(s => s.unsubscribe());
    this.subscriptions = [];
    this.slot().clear(); // destroys every component in the container
    this.refs = [];
  }
}

A few points that older tutorials get wrong:

  • Use ref.setInput(), not direct assignment. Writing ref.instance.listId = 'x' doesn't work at all with signal inputs. With decorator inputs it skips ngOnChanges and doesn't mark an OnPush component for checking, so the view can stay stale. setInput() behaves exactly like a template binding.
  • ComponentFactoryResolver is no longer needed. createComponent() takes the component class directly. The factory API has been deprecated since Angular 13.
  • clear() destroys the components. Every component created in a container is destroyed when the container is cleared, or when the host component is destroyed. Call ref.destroy() yourself only for one component you want to remove while keeping the others.

⚠️ Common mistake: Creating components from inside an ngOnInit that runs before the anchor exists, or using @ViewChild without { static: true } and reading it too early. With viewChild.required() and an effect(), as above, the container is guaranteed to exist when render() runs.

Lazy Loading Widgets

Importing every widget class at the top of the dashboard puts all of them in the dashboard's bundle. A registry of loader functions defers each widget's code until it's used:

TypeScript
const WIDGET_LOADERS: Record<WidgetConfig['type'], () => Promise<Type<unknown>>> = {
  'sales-chart': () => import('./sales-chart.component').then(m => m.SalesChartComponent),
  'todo-list': () => import('./todo-list.component').then(m => m.TodoListComponent),
};

// Inside render(): await the class, then create it as before.
const component = await WIDGET_LOADERS[config.type]();
const ref = this.slot().createComponent(component);

Because render() is now asynchronous, guard against an older render finishing after a newer one (for example, keep a render counter and ignore results from outdated runs).

If the set of components is known at build time and you only want to delay loading, @defer blocks are simpler. @defer (on viewport) { <app-sales-chart /> } splits that component into its own chunk without any manual import() calls.

💡 Tip: Keep the registry typed by the config's type union, as in Record<WidgetConfig['type'], ...>. Adding a new widget type to WidgetConfig then produces a compile error until the registry has an entry for it.

Summary

  • Use NgComponentOutlet with inputs when you only need to render a component chosen at runtime.
  • Use ViewContainerRef.createComponent() when you also need outputs or fine-grained control, and pass inputs with setInput().
  • Let clear() and host destruction clean up components, and unsubscribe from outputs you subscribed to.
  • Load widget code on demand with a registry of import() functions, or use @defer when the components are known at build time.
Advertisement