Sub topic 8
Projected content is created eagerly
This chapter assumes you can write Angular standalone components, use ng-content with a single slot, and read the @if control flow syntax. You should also know that a component's constructor and ngOnInit run when Angular creates it.
The surprise
A common first guess is that ng-content inside an @if block works like the rest of that block. If the condition is false, nothing inside should exist. For projected content this is wrong.
Here is a wrapper that shows its content only when open is true.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-collapsible',
template: `
<div class="box">
@if (open()) {
<ng-content />
}
</div>
`,
})
export class CollapsibleComponent {
open = input(false);
}Now a child that reports when it is created.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-heavy-widget',
template: `<p>Heavy widget</p>`,
})
export class HeavyWidgetComponent implements OnInit {
constructor() {
console.log('HeavyWidget constructor');
}
ngOnInit() {
console.log('HeavyWidget ngOnInit');
}
}Finally a parent that uses both with open set to false.
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 [open]="false">
<app-heavy-widget />
</app-collapsible>
`,
})
export class AppComponent {}When you load this page, the console prints both log lines, even though the widget never appears on screen.
Why this happens
The parent's template owns <app-heavy-widget />. When Angular renders the parent, it creates every node written in that template, including nodes between the app-collapsible tags. The child component only decides where those existing nodes are attached. If ng-content is not rendered, the nodes stay created but detached from the DOM.
This follows from the ownership rule in the previous chapter. The parent creates the content, binds it, and runs change detection on it. The wrapper only positions it.
What stays active
Detached projected content is not frozen. These things still happen:
- Constructors and
ngOnInitrun once, at parent render time. - Input bindings in the parent template keep updating the projected component.
- Effects, subscriptions, and timers started by the projected component keep running.
- Any HTTP request that the component starts in
ngOnInitis sent.
If the widget fetches a large dataset on startup, a closed wrapper still triggers that request.
Toggling does not recreate content
The reverse also holds. Switching open from true to false and back does not destroy and rebuild the widget. The same instances are attached and detached, so their state survives. This can be useful, because a form inside a collapsed panel keeps what the user typed.
Fixing it with ng-template
To delay creation, have the parent pass an ng-template. A template is a recipe, and Angular builds nothing from it until someone renders it. The wrapper from the earlier chapter spec does this with ngTemplateOutlet.
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 writes this:
<app-lazy-box [open]="isOpen">
<ng-template>
<app-heavy-widget />
</ng-template>
</app-lazy-box>Now the widget's constructor runs only when open becomes true. When it becomes false again, Angular destroys the widget, so state is lost. The next chapter section on ng-template covers this trade-off in more detail.
| Approach | Created when | State on toggle | Typical use |
|---|---|---|---|
| `ng-content` inside `@if` | Parent renders | Kept | Cheap content, state worth keeping |
| `ng-template` with `ngTemplateOutlet` | Wrapper renders the template | Lost on hide | Heavy or data-fetching content |
Common errors
- Expecting no side effects from hidden content. Tabs, accordions, and dialogs built with
ng-contentstart all their children's requests at once. - Putting
ng-contentin two branches and expecting both to show it. A projected node exists once and can sit in only one place. For repeated content, use a template. - Moving expensive work into the constructor of a widget. Even with templates, keep constructors light so creation stays cheap.
Exercise
A dialog component wraps its ng-content in @if (visible()). Its parent places a <app-report /> component inside the dialog, and app-report calls an HTTP endpoint in ngOnInit. The dialog is never opened. Is the request sent, and what change to the parent's markup would prevent it?
Show answer
Yes, the request is sent. The parent creates app-report when it renders, so ngOnInit runs even though the dialog never attaches the content. To prevent it, the dialog should read a template with contentChild(TemplateRef) and render it using ngTemplateOutlet inside the @if. The parent then wraps <app-report /> in an <ng-template>, so the component is only created when the dialog is opened.