Sub topic 8
Projected content is created eagerly
This chapter assumes you can write standalone Angular components, use ng-content with and without select, and read basic lifecycle hooks such as ngOnInit. It covers a rule that surprises many developers: putting <ng-content> inside an @if does not stop the projected content from being created.
The surprise
Suppose you build a collapsible panel. It is natural to write the body like this:
import { Component, input } from '@angular/core';
@Component({
selector: 'app-collapsible',
template: `
<h3>{{ heading() }}</h3>
@if (open()) {
<ng-content />
}
`,
})
export class CollapsibleComponent {
heading = input('Details');
open = input(false);
}You would expect that with open set to false, whatever the parent places inside the panel never comes into existence. That expectation is wrong. To see why, add a child component that reports its own lifecycle:
import { Component, OnDestroy, OnInit } from '@angular/core';
@Component({
selector: 'app-heavy-widget',
template: `<p>Expensive widget</p>`,
})
export class HeavyWidgetComponent implements OnInit, OnDestroy {
constructor() {
console.log('HeavyWidget: constructor');
}
ngOnInit() {
console.log('HeavyWidget: ngOnInit');
// Imagine an HTTP request or a timer starting here.
}
ngOnDestroy() {
console.log('HeavyWidget: ngOnDestroy');
}
}Now use both in a parent with the panel closed:
import { Component } from '@angular/core';
import { CollapsibleComponent } from './collapsible.component';
import { HeavyWidgetComponent } from './heavy-widget.component';
@Component({
selector: 'app-root',
imports: [CollapsibleComponent, HeavyWidgetComponent],
template: `
<app-collapsible heading="Report" [open]="false">
<app-heavy-widget />
</app-collapsible>
`,
})
export class AppComponent {}When the page loads, the console prints both HeavyWidget: constructor and HeavyWidget: ngOnInit. The panel is closed and the widget is not visible, but it exists.
Why this happens
The parent template declares <app-heavy-widget />. Angular treats everything between <app-collapsible> and </app-collapsible> as part of the parent's view, so the parent creates it. This is the ownership rule from the previous chapter: the parent creates projected content, binds it, and checks it for changes.
<ng-content> is not an instruction to create anything. It marks a place where already-created nodes can be inserted into the DOM. The @if around it controls only whether those nodes are attached at that place.
The order of events is:
- The parent view is created. This creates the
app-collapsiblehost and theapp-heavy-widgetinstance inside it. - The panel's template runs. The
@ifis false, so no insertion point is rendered. - The widget exists, runs its lifecycle hooks, and is checked for changes with the parent. It is not attached to the document.
- If
openlater becomestrue, Angular attaches the existing widget nodes at theng-contentposition. It does not create a new instance.
What this means in practice
The following all happen whether or not the slot is displayed:
- Constructors run, and
ngOnInitand other lifecycle hooks fire. - Inputs on projected components are bound and updated.
- Dependency injection resolves and services are instantiated.
- Side effects run, such as HTTP calls, timers, and subscriptions.
- Content queries in the receiving component can find the projected components.
The following does not happen: the nodes do not appear in the DOM, so users cannot see them.
The same rule applies elsewhere
The behavior is consistent across other ways of wrapping a slot.
| Wrapper around `ng-content` | Is projected content created? | Is it shown? |
|---|---|---|
| `@if (false)` | Yes | No |
| `@if (true)` | Yes | Yes |
| `@for` over several items | Yes, once | The nodes appear in one place only |
| No matching slot and no default slot | Yes | No |
| `[hidden]` or CSS `display: none` on a wrapper | Yes | Not visible, but in the DOM |
The last two rows deserve attention. If a parent supplies content with an attribute that matches no select and the component has no default <ng-content />, that content is still created. It has nowhere to go. This can be a silent bug: a typo such as panel-titel creates the element and then discards it from view.
The @for row is a related trap. Content is projected once, so wrapping <ng-content /> in @for does not stamp out copies of the content. Do not use it to repeat content.
Seeing it with a destroy test
You can also watch the destroy side. Here is a parent that toggles the panel itself:
import { Component, signal } from '@angular/core';
import { CollapsibleComponent } from './collapsible.component';
import { HeavyWidgetComponent } from './heavy-widget.component';
@Component({
selector: 'app-root',
imports: [CollapsibleComponent, HeavyWidgetComponent],
template: `
<button (click)="open.set(!open())">Toggle panel</button>
<app-collapsible heading="Report" [open]="open()">
<app-heavy-widget />
</app-collapsible>
`,
})
export class AppComponent {
open = signal(false);
}Click the button several times. The console shows the constructor and ngOnInit once, at startup. It never shows ngOnDestroy while you toggle, because closing the panel only detaches the nodes. The widget lives as long as the parent view does.
If you need to see destruction and recreation, the parent must be the one that conditionally declares the content, as the next section shows.
Fix 1: let the parent decide
The simplest fix puts the condition in the parent, where the content is declared:
import { Component, signal } from '@angular/core';
import { CollapsibleComponent } from './collapsible.component';
import { HeavyWidgetComponent } from './heavy-widget.component';
@Component({
selector: 'app-root',
imports: [CollapsibleComponent, HeavyWidgetComponent],
template: `
<button (click)="open.set(!open())">Toggle panel</button>
<app-collapsible heading="Report" [open]="open()">
@if (open()) {
<app-heavy-widget />
}
</app-collapsible>
`,
})
export class AppComponent {
open = signal(false);
}Now the widget is created when open becomes true and destroyed when it becomes false. The cost is that every user of app-collapsible must remember to repeat the condition. If they forget, they get the eager behavior, and nothing warns them.
Fix 2: accept an ng-template
When you own the wrapper component and want laziness to be built in, ask the parent for a template instead of plain content. A template is a recipe. Declaring it creates nothing. The recipe is run only when something renders it.
import { Component, TemplateRef, contentChild, input } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
@Component({
selector: 'app-lazy-box',
imports: [NgTemplateOutlet],
template: `
@if (open()) {
<ng-container [ngTemplateOutlet]="body()" />
}
`,
})
export class LazyBoxComponent {
open = input(false);
body = contentChild.required(TemplateRef);
}The parent wraps its content in <ng-template>:
import { Component, signal } from '@angular/core';
import { LazyBoxComponent } from './lazy-box.component';
import { HeavyWidgetComponent } from './heavy-widget.component';
@Component({
selector: 'app-root',
imports: [LazyBoxComponent, HeavyWidgetComponent],
template: `
<button (click)="open.set(!open())">Toggle</button>
<app-lazy-box [open]="open()">
<ng-template>
<app-heavy-widget />
</ng-template>
</app-lazy-box>
`,
})
export class AppComponent {
open = signal(false);
}The console now stays silent until the first click. The widget's constructor runs when the box renders the template. Each time open goes from true to false, the rendered view is destroyed and ngOnDestroy runs. The next true creates a fresh instance.
Two details are worth knowing:
- The template still belongs to the parent's declaration context. Bindings inside it resolve against the parent component, not against
LazyBoxComponent. contentChild.required(TemplateRef)throws if the parent supplies no template. UsecontentChild(TemplateRef)and check forundefinedif the template is optional.
Choosing between the two
| Question | `ng-content` | `ng-template` with `ngTemplateOutlet` |
|---|---|---|
| When is content created? | When the parent view is created | When the receiver renders the template |
| Can it be destroyed and recreated by the receiver? | No | Yes |
| Can it appear several times? | No, one insertion point | Yes, render the template as often as needed |
| Can the receiver pass data in? | No | Yes, through a template context |
| How much does the parent write? | Plain markup | Markup wrapped in `<ng-template>` |
| Typical use | Cards, layouts, wrappers | Lazy panels, dialogs, list items, tab bodies |
Prefer plain ng-content when the content is cheap and should always exist, such as card bodies, headers, and layout wrappers. Use a template when the content is expensive, when it should be torn down on close, or when the receiver must render it more than once or with its own data.
Edge cases and gotchas
Content queries still see hidden content. Because the projected components exist, a contentChildren(TabComponent) in the receiver lists every tab, including those in a slot that is not rendered. That makes it easy to build navigation from them. It also means you cannot use the query's result as a signal that something is visible.
Change detection still runs. Projected components are part of the parent's view. Their bindings are evaluated during the parent's checks even when their nodes are detached. Hidden does not mean idle.
Subscriptions and timers leak in time, not in space. A hidden widget that polls an API every second keeps polling. If you only notice this through network traffic, check whether the widget sits behind an ng-content inside an @if.
Reattachment preserves state. Because the instance is reused, toggling the slot keeps form values, scroll positions held in component fields, and other local state. This is sometimes a benefit. If you want a clean state on each open, use the template approach.
Fallback content is different. Content written between <ng-content> and </ng-content> is created by the receiver and appears only when nothing is projected. That fallback is not eager in the same way, so do not conflate the two.
Summary of the rule
The parent creates projected content when the parent's view is created. The receiver's ng-content only decides whether and where the nodes are attached. If the content must not exist until it is needed, move the condition into the parent or switch to ng-template.
Exercise
A PanelComponent template contains @if (expanded()) { <ng-content /> }. A parent uses <app-panel [expanded]="false"><app-chart /></app-panel>, and ChartComponent fetches data in ngOnInit. Does the fetch run? What would you change so it runs only when the panel is expanded, without changing the parent's markup shape beyond what you must?
Show answer
Yes, the fetch runs on startup. The parent view creates app-chart as soon as the parent renders, and the @if inside the panel only controls whether the nodes are attached. To defer it, either have the parent wrap the chart in @if (isExpanded) { <app-chart /> }, or change the panel to accept an <ng-template> through contentChild.required(TemplateRef) and render it with ngTemplateOutlet inside the @if. The parent then wraps the chart in <ng-template>.
Exercise
You switch LazyBoxComponent to the template approach, and a teammate notices that closing and reopening the box resets a text field inside it, while the old ng-content version kept the typed text. Explain why, and say how you would keep the text with the template version.
Show answer
With ng-content, the projected component instance is created once and only detached and reattached, so its state survives. With ngTemplateOutlet inside an @if, the rendered view is destroyed on close and a new one is created on reopen, so local state is lost. To keep the text, store it outside the destroyed view, for example in a signal or model on the parent or a service, and bind the field to it. Alternatively, hide the rendered template with CSS instead of removing it with @if.