الانتقال إلى المحتوى
FrontendAngular· 7 دقائق للقراءة

Hiding <ng-content> Doesn't Stop It Being Created: Content Projection Pitfalls

The parent creates projected content whether or not it's shown. Pass an ng-template when it should be lazy.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • Angular 22
محتويات المقال

A settings page has five collapsible sections, all closed by default, built with a small <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

The belief: <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.

That's a reasonable reading of the 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

With , the children you write between <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.

So @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.

TypeScript expander.ts
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);}

Pass a template instead of content

An <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:

HTML settings-page.html
<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

Because projected content is part of the parent's view, two more rules follow, and the guide lists both. Change detection: it's checked when the parent is checked, and the expander's OnPush, the default since v22, lets Angular skip only the expander's own template, never the projected content. Dependency injection: projected content gets its dependencies from the parent's injector, not from the expander's 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
CreatedWith the parent, at loadWhen the outlet renders it
When hiddenOut of the DOM, still aliveDestroyed
ngOnInit and requestsRun even if never shownRun only when shown
State on reopenKeptStarts over
Good forContent that's always visibleOptional, heavy or lazy content

How to apply it in your project

  1. Find conditional placeholdersSearch templates for <ng-content and look for any that sit inside @if, @for, @switch or a tab or accordion body. Each one is content that's created up front.
  2. Decide what the content needsIf 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.
  3. Switch heavy slots to templatesQuery the caller's <ng-template> with contentChild() and render it with ngTemplateOutlet inside your @if. Update the callers to wrap their content in <ng-template>.
  4. Confirm with a logPut a console.log in the projected component's ngOnInit and ngOnDestroy, 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.
  • @if around <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 with ngTemplateOutlet.
  • Projected content is checked with the parent and injects from the parent's side, so the wrapper's OnPush and viewProviders don't apply to it.

📚 المصادر

  1. Content projection with ng-content — Angular
  2. Create template fragments with ng-template — Angular
  3. Referencing component children with queries — Angular
  4. NgTemplateOutlet — Angular API

التعليقات (0)