Sub topic 11
Projecting nodes into dynamically created components
This chapter assumes you know ng-content, the select attribute, and how ng-template works. So far, every projected node came from a parent template. Angular matched the parent's content to the slots at compile time. A component created from code has no parent template, so there is nothing to match. You give Angular the nodes yourself.
Why static projection does not apply
When you write <app-dialog>...</app-dialog> in a template, the compiler sees the children and sorts them into slots. That sorting is baked into the compiled parent template.
When you call createComponent or ViewContainerRef.createComponent, no tags exist between the component's tags. Typical cases are modals, toasts, overlays, and a router-like outlet that picks a component at runtime. The component's own template still contains ng-content slots, and they stay empty unless you pass nodes.
The option that supplies them is projectableNodes. It is an array of arrays of DOM nodes.
The `projectableNodes` contract
Each inner array fills one ng-content slot. Three rules matter:
- The outer array is indexed by the order in which
ng-contentelements appear in the component's template, from top to bottom. - Angular does not evaluate
selectfor these nodes. Theselectattribute decides how compile-time children are sorted. WithprojectableNodes, your index decides the slot. - The nodes must be real DOM nodes (
Nodeobjects), not strings or HTML.
For this template:
<header><ng-content select="[dialog-title]" /></header>
<section><ng-content /></section>
<footer><ng-content select="[dialog-actions]" /></footer>The indexes are:
| Index | Slot | Selector |
|---|---|---|
| 0 | header | `[dialog-title]` |
| 1 | section | default (no `select`) |
| 2 | footer | `[dialog-actions]` |
The order comes from the template, not from the selectors. If you move the default slot above the title slot, the indexes swap. Treat the order of slots as part of the component's public API once anyone creates it dynamically.
A first example with plain DOM nodes
The component below has two slots. The host creates it with ViewContainerRef and passes one element per slot.
import { Component, ViewContainerRef, inject } from '@angular/core';
@Component({
selector: 'app-dialog',
template: `
<header><ng-content select="[dialog-title]" /></header>
<section><ng-content>No content</ng-content></section>
`,
})
export class DialogComponent {}
@Component({
selector: 'app-host',
template: `<button (click)="open()">Open dialog</button>`,
})
export class HostComponent {
private readonly container = inject(ViewContainerRef);
open(): void {
const title = document.createElement('h2');
title.textContent = 'Saved';
const body = document.createElement('p');
body.textContent = 'Your changes were stored.';
this.container.createComponent(DialogComponent, {
projectableNodes: [[title], [body]],
});
}
}title goes to index 0 and body to index 1. The dialog-title attribute is not needed, because index 0 already selects the header slot. Adding it is harmless.
Raw DOM nodes are static. They have no template bindings, no directives, and no pipes. That is fine for a message, but it is a poor fit for anything that needs data binding. For that, build the nodes from a template.
Building nodes from an `ng-template`
An embedded view created from a TemplateRef has a rootNodes array. Those nodes are compiled template output, so bindings, directives and control flow all work.
import {
ApplicationRef,
Component,
EmbeddedViewRef,
TemplateRef,
ViewContainerRef,
inject,
signal,
viewChild,
} from '@angular/core';
@Component({
selector: 'app-dialog',
template: `
<header><ng-content select="[dialog-title]" /></header>
<section><ng-content /></section>
`,
})
export class DialogComponent {}
@Component({
selector: 'app-counter-host',
template: `
<ng-template #bodyTpl let-name>
<p>Hello {{ name }}, you clicked {{ count() }} times.</p>
</ng-template>
<button (click)="count.set(count() + 1)">Click</button>
<button (click)="open()">Open</button>
<button (click)="close()">Close</button>
`,
})
export class CounterHostComponent {
private readonly container = inject(ViewContainerRef);
private readonly appRef = inject(ApplicationRef);
private readonly bodyTpl = viewChild.required<TemplateRef<{ $implicit: string }>>('bodyTpl');
readonly count = signal(0);
private view?: EmbeddedViewRef<{ $implicit: string }>;
private dialog?: ReturnType<ViewContainerRef['createComponent']>;
open(): void {
if (this.dialog) return;
this.view = this.bodyTpl().createEmbeddedView({ $implicit: 'Ada' });
this.appRef.attachView(this.view);
this.dialog = this.container.createComponent(DialogComponent, {
projectableNodes: [[], this.view.rootNodes],
});
}
close(): void {
this.dialog?.destroy();
if (this.view) {
this.appRef.detachView(this.view);
this.view.destroy();
}
this.dialog = undefined;
this.view = undefined;
}
}Four details in this code are easy to miss.
- The first inner array is empty. It leaves the title slot with no nodes, so any fallback content in that slot is rendered instead.
createEmbeddedViewon aTemplateRefcreates the view but does not insert it anywhere. Its nodes sit detached until projection moves them into the dialog.- A detached view is not checked for changes on its own.
appRef.attachViewregisters it with the application's change detection, so{{ count() }}updates. Without that call the text would stay frozen at its first value. - Destroying the dialog does not destroy your view. You created it, so you destroy it. Skipping this leaks the view and its subscriptions.
Because the template is declared in CounterHostComponent, the host owns the bindings. This matches the ownership rule from the earlier chapter on who owns projected content: the creator of the content is responsible for its context and lifetime.
Creating a component outside any view container
An overlay normally lives at the end of body, not inside the host's view. The standalone createComponent function covers this. It needs an EnvironmentInjector and does not insert the component anywhere.
import {
ApplicationRef,
ComponentRef,
EnvironmentInjector,
Injectable,
createComponent,
inject,
} from '@angular/core';
import { DialogComponent } from './dialog.component';
@Injectable({ providedIn: 'root' })
export class DialogService {
private readonly appRef = inject(ApplicationRef);
private readonly injector = inject(EnvironmentInjector);
show(message: string): ComponentRef<DialogComponent> {
const text = document.createElement('p');
text.textContent = message;
const ref = createComponent(DialogComponent, {
environmentInjector: this.injector,
projectableNodes: [[], [text]],
});
this.appRef.attachView(ref.hostView);
document.body.appendChild(ref.location.nativeElement);
return ref;
}
hide(ref: ComponentRef<DialogComponent>): void {
this.appRef.detachView(ref.hostView);
ref.destroy();
}
}You perform three steps by hand here that a view container does for you: attach to change detection, attach to the DOM, and clean up on close. ref.location.nativeElement is the host element, the app-dialog element that wraps the component's template.
`ngComponentOutlet` with content
If the component is chosen in a template, you can skip the imperative code. NgComponentOutlet accepts the same array of arrays through its ngComponentOutletContent input.
import { Component, signal } from '@angular/core';
import { NgComponentOutlet } from '@angular/common';
import { DialogComponent } from './dialog.component';
@Component({
selector: 'app-outlet-host',
imports: [NgComponentOutlet],
template: `
<ng-container *ngComponentOutlet="dialog; content: nodes()" />
`,
})
export class OutletHostComponent {
readonly dialog = DialogComponent;
readonly nodes = signal<Node[][]>(this.buildNodes());
private buildNodes(): Node[][] {
const title = document.createElement('h2');
title.textContent = 'From the outlet';
return [[title], [document.createTextNode('Plain body text')]];
}
}The nodes are read when the component is created. Changing nodes() later does not rebuild the existing component. The outlet recreates the component only when the component type or its injector changes. When the content must change, build a new nodes array and also change the component or injector, or manage the component yourself with createComponent.
What dynamic projection does not give you
Several features you rely on with static projection do not carry over.
No `select` matching
You cannot rely on select, ngProjectAs, or the catch-all rule, because index alone decides placement. A wrong index puts content in the wrong slot with no error. If you pass more inner arrays than the template has slots, the extra arrays are ignored.
No content queries
contentChild and contentChildren find components that a parent template declared between the tags. Nodes you pass in projectableNodes were never declared there, so content queries in the dynamic component return nothing for them. A component that builds navigation from contentChildren(TabComponent) will show no tabs when created this way. If the component must work in both modes, give it an input (for example tabs = input<TabDef[]>([])) as the dynamic-friendly alternative.
One node, one slot
A DOM node can only live in one place. If you project the same node into two slots, or into two component instances, it moves and ends up in the last place only. For repeated content, create a new embedded view from the template each time.
Manual lifecycle
Projection only moves nodes. It does not own them. Destroying the component removes its own DOM, but the embedded views you created with createEmbeddedView stay alive until you call destroy() on them. Pair every createEmbeddedView with a destroy(), and every attachView with a detachView.
Choosing an approach
| Situation | Best fit |
|---|---|
| Content is known in the parent's template | Static `ng-content` |
| Content is chosen at runtime, no data binding | `createElement` nodes with `projectableNodes` |
| Content needs bindings or directives | `ng-template` plus `createEmbeddedView().rootNodes` |
| Component is chosen in a template | `ngComponentOutlet` with `content` |
| Content must be created lazily or many times | `ng-template` passed as an input, rendered with `ngTemplateOutlet` |
The last row is often the cleanest design. If the dynamic component takes a TemplateRef input and renders it with ngTemplateOutlet, you never touch DOM nodes. You also do not depend on slot order, and the template's creation and destruction follow the outlet's own lifecycle. Use projectableNodes when you must reuse a component whose design is already fixed around ng-content, or when you integrate with code that already works with DOM nodes.
Common errors
- Slots swapped or empty. The indexes follow the order of
ng-contentin the template, not selector order. Re-read the template and count. - Bindings stay stale. The embedded view was never attached with
appRef.attachView, or it was inserted nowhere and no change detection reached it. NG0203-style injection errors when callingcreateComponent. The standalone function needsenvironmentInjector. Provide one by injectingEnvironmentInjector.- Leaked views. The dialog closed but the template view was never destroyed.
- Passing a string such as
'<b>hi</b>'. The array holdsNodeobjects only. Create nodes withdocument.createElementordocument.createTextNode.
Exercise
A component template has <ng-content select="[a]" />, then <ng-content />, then <ng-content select="[c]" />. You want to project one <p> into the last slot only and leave the other two empty. What do you pass as projectableNodes?
Show answer
[[], [], [p]]. The outer array is indexed by the position of each ng-content in the template. The first two inner arrays are empty, so any fallback content in those slots is shown, and p goes to index 2, the [c] slot. The select selector is not evaluated for these nodes.
Exercise
You build a dialog's body with templateRef.createEmbeddedView(ctx) and pass view.rootNodes to projectableNodes. The text renders once but never updates when a signal in the template changes, and after closing the dialog memory use grows. Name the two missing calls.
Show answer
Call appRef.attachView(view) after creating the view, so change detection runs for it, and call view.destroy() (after appRef.detachView(view)) when the dialog closes. Projection only moves the nodes. It neither checks the view for changes nor destroys it.
Exercise
A TabsComponent builds its tab buttons from contentChildren(TabComponent). You create it with createComponent and project the tab elements through projectableNodes. Why are no buttons shown, and what is a design that works in both cases?
Show answer
Content queries only see components declared as content in a parent template. Nodes passed through projectableNodes were never declared that way, so the query is empty. Add an input such as tabs = input<TabDef[]>([]) and have the component use it when the query result is empty, or render the tab list from the input in dynamic use.