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.
-
NgComponentOutletin 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. -
ViewContainerRef.createComponent(Type): gives aComponentRef. Get a container withviewChild('host', { read: ViewContainerRef })on anng-containerordiv. Then:ref.setInput('message', 'Saved')sets inputs (works with signal inputs, and triggers OnPush updates).ref.instance.closed.subscribe(...)listens to anoutput().ref.destroy()removes it. Destroying the container, or its host component, also destroys the children.
-
The standalone
createComponent(Type, { environmentInjector, hostElement })plusApplicationRef.attachView(ref.hostView)creates a component outside any template. This is the approach for overlays that attach todocument.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.
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.