Sub topic 3
Projected Content Is Created Eagerly
Assume basic Angular components, templates, CSS selectors, and TypeScript. Content projection changes where parent markup appears. It does not transfer ownership of that markup to the child.
Projected content is created eagerly
Angular creates and binds projected content when the parent view is created. This remains true even if the child places ng-content inside a conditional block.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-panel',
template: `
@if (showBody()) {
<ng-content />
}
`,
})
export class PanelComponent {
showBody = input(true);
}When showBody is false, the content is not displayed, but the parent still owns its creation and bindings. Do not use conditional ng-content to implement lazy loading.
Reading projected content with content queries
A content query reads components or directives projected into a component. contentChild returns one match, while contentChildren returns a signal containing all matching children.
import { Component, contentChildren, input } from '@angular/core';
@Component({
selector: 'app-tab',
template: `<ng-content />`,
})
export class TabComponent {
title = input.required<string>();
}
@Component({
selector: 'app-tabs',
template: `
<nav>
@for (tab of tabs(); track tab) {
<button>{{ tab.title() }}</button>
}
</nav>
<ng-content />
`,
})
export class TabsComponent {
tabs = contentChildren(TabComponent);
}The query finds projected app-tab components, not arbitrary descendants in the component's own view.
Lazy and repeated content with ng-template
An ng-template stores a template without creating its elements. ngTemplateOutlet creates that template when requested and can create it repeatedly. This is the appropriate pattern for expensive or optional content.
The template can also receive a context when rendered, allowing repeated instances to use different values.
Projecting nodes into dynamically created components
Code that creates a component dynamically can provide DOM nodes through the projectableNodes option. Angular assigns each node array to a matching ng-content slot. This is a low-level technique; prefer normal templates when the structure is known.
Pitfalls and design guidelines
- Do not expect a hidden
ng-contentslot to save creation or memory. - Use distinct
selectselectors so slot ownership is clear. - Use content queries for projected components, not to inspect the child’s private view.
- Prefer
ng-templatefor lazy, repeated, or conditionally created content. - Keep dynamic node projection for framework-level or highly dynamic composition.
Exercise
A projected widget should be created only after a user opens a panel. Should the panel use conditional ng-content or ng-template?
Show answer
Use ng-template with ngTemplateOutlet. Conditional ng-content hides the result but does not delay creation.