
Hiding <ng-content> Doesn't Stop It Being Created: Content Projection Pitfalls
- كاتب موثّق
- Angular 22
محتويات المقال
<app-expander> that wraps its <ng-content> in @if (open()). The Network panel shows five API calls on page load anyway, one per section, including the audit log that downloads its full history. A teammate adds a console.log to the audit log's ngOnInit: it prints at startup, before anyone clicks. Closing the section later doesn't call ngOnDestroy either, so its polling timer keeps running on a page where nobody can see it.
The common misconception
<ng-content> is a slot that gets filled when it renders, so @if (open()) { <ng-content /> } means the projected content is created when the panel opens and destroyed when it closes, the same way @if treats the expander's own template.
@if really does create and destroy whatever it contains, and <ng-content> sits inside it, so it looks like the content goes with it. Developers who know React have a second reason: there, {open && children} really doesn't mount the children until open is true. And for plain text or a few static elements, nothing visible goes wrong: the content shows when it should, so nobody checks when it was created.
What actually happens
The parent builds the content; the child only places it
<app-expander> tags are still part of the parent's template. Angular creates them while it creates the parent's view, in the same pass as the parent's other elements, and they're owned by that view for their whole life. The expander receives nodes that already exist. Its <ng-content> is a placeholder that tells Angular where to put them, and Angular's compiler processes those placeholders at build time; they can't be added or removed at run time.
@if around <ng-content> controls placement, not existence. The content guide says it plainly: Angular always instantiates and creates DOM nodes for content projected into an <ng-content>, even if that placeholder is hidden, and you shouldn't put <ng-content> inside @if, @for or @switch. When the condition turns false, the projected nodes leave the DOM, but the components behind them stay alive with the parent's view. Their constructors ran at page load, their ngOnInit ran, their subscriptions and timers continue, and ngOnDestroy waits until the parent itself is destroyed.
import { Component, input, signal } from '@angular/core';@Component({ selector: 'app-expander', template: ` <button (click)="open.set(!open())">{{ label() }}</button> @if (open()) { <!-- Hides the content; it was created with the parent --> <ng-content /> } `,})export class Expander { readonly label = input.required<string>(); readonly open = signal(false);}import { NgTemplateOutlet } from '@angular/common';import { Component, TemplateRef, contentChild, input, signal,} from '@angular/core';@Component({ selector: 'app-expander', imports: [NgTemplateOutlet], template: ` <button (click)="open.set(!open())">{{ label() }}</button> @if (open()) { <ng-container [ngTemplateOutlet]="body()" /> } `,})export class Expander { readonly label = input.required<string>(); readonly open = signal(false); // The caller's <ng-template>: rendered on open, destroyed on close readonly body = contentChild(TemplateRef);}Pass a template instead of content
<ng-template> is a description of content, not content. Angular doesn't render anything inside it until some code asks for it, so the caller can hand the expander a and let the expander decide when it exists:
<app-expander label="Audit log"> <ng-template> <app-audit-log /> </ng-template></app-expander>contentChild(TemplateRef) finds that template, and ngTemplateOutlet creates a fresh view from it each time the @if turns true. When it turns false, the @if destroys its block and the view the outlet created with it, so the audit log runs ngOnDestroy and its timer stops. Bindings inside the template are still evaluated against the settings page that declared it, so {{ ... }} and event handlers work exactly as they did before. The trade-off runs the other way now: closing the panel throws away whatever state the content had, so a reopened audit log starts over and loads its data again.
Ownership has other effects
viewProviders. A template rendered by ngTemplateOutlet also takes its injector from where it was declared, unless you pass ngTemplateOutletInjector.
<ng-content> inside @if | <ng-template> + ngTemplateOutlet | |
|---|---|---|
ngOnInit and requests | ||
How to apply it in your project
Find conditional placeholders Search templates for <ng-contentand look for any that sit inside@if,@for,@switchor a tab or accordion body. Each one is content that's created up front.Decide what the content needs If it's cheap and should keep its state across toggles, like a half-filled form, keep it projected and stop expecting it to be lazy. If it loads data, runs timers or is rarely opened, switch it to a template. Switch heavy slots to templates Query the caller's <ng-template>withcontentChild()and render it withngTemplateOutletinside your@if. Update the callers to wrap their content in<ng-template>.Confirm with a log Put a console.login the projected component'sngOnInitandngOnDestroy, reload, and toggle the panel. Both should fire on open and close, not at page load.
Key takeaways
Projected content is created by the parent with the parent's view, whether or not it's ever shown. @ifaround<ng-content>only moves nodes in and out of the DOM; the components inside keep running.For content that should exist only while it's visible, accept an <ng-template>and render it withngTemplateOutlet.Projected content is checked with the parent and injects from the parent's side, so the wrapper's OnPush and viewProvidersdon't apply to it.
التعليقات (0)