Sub topic 12
Pitfalls and design guidelines
This chapter collects the mistakes that most often cause trouble with ng-content, and the design rules that avoid them. It assumes you can write Angular components with signal inputs, that you know the select attribute, ngProjectAs, fallback content and content queries from the earlier chapters, and that you can read CSS selectors.
Most pitfalls come from one fact: the parent owns projected content. The parent creates it, binds it and styles it. The component that hosts the <ng-content> only decides where the content is placed in the DOM.
Pitfall 1: `select` matches only top-level nodes
Angular compares each select selector against the direct children of the component's tag in the parent template. It does not look at their descendants. Consider this usage of the app-panel from earlier chapters:
<app-panel>
<div class="heading-wrapper">
<h2 panel-title>Settings</h2>
</div>
<button panel-actions>Save</button>
</app-panel>The div is the only direct child that is not the button. It matches no selector, so it goes to the default slot, and the h2 goes with it. The panel-title attribute is never examined. The title appears in the body, not the header.
There are three fixes:
- Remove the wrapper so the
h2is a direct child. - Put the attribute on the wrapper:
<div panel-title>. - Use
ngProjectAson anng-containerwhen you need several elements without a wrapper.
<app-panel>
<ng-container ngProjectAs="[panel-title]">
<h2>Settings</h2>
<small>beta</small>
</ng-container>
<p>Body text</p>
</app-panel>Pitfall 2: everything unmatched falls into the default slot
The default slot is a <ng-content /> with no select. It receives every top-level node that no other slot claims. That includes text nodes, elements with a typo in the attribute name, and elements whose selector you forgot to add to the component.
A typo such as panel-action instead of panel-actions does not raise an error. The button silently appears in the body. Two habits help:
- Keep slot names in one place. Document them in a comment above the component, or export constants for the attribute names.
- Look at the rendered page after adding a slot. The compiler cannot tell you that a node landed in the wrong place.
Two cases surprise people.
Control flow. A @if or @for block is not an element. In recent Angular versions, a block whose body has a single root element can be matched against select using that root element. A block with several root nodes goes to the default slot. If you depend on this, check the behavior in the Angular version you use. A wrapping ng-container ngProjectAs states the intent explicitly and works in every version.
Whitespace. By default Angular removes whitespace-only text nodes in templates, so indentation does not stop the fallback content from showing. If you set preserveWhitespaces: true, whitespace text in the default slot can make the slot count as filled.
Pitfall 3: duplicate selectors project into only one place
A projected node can exist in the DOM only once. If two <ng-content> elements could both match the same node, only one of them receives it. Do not write this:
import { Component } from '@angular/core';
@Component({
selector: 'app-broken-card',
template: `
<header><ng-content select="[card-title]" /></header>
<nav><ng-content select="[card-title]" /></nav>
`,
})
export class BrokenCardComponent {}The title appears in one of the two places. In practice it is the last matching slot, but do not rely on that. The same restriction means you cannot repeat <ng-content> inside a @for to render the content several times. When you need to render the same content more than once, accept an ng-template instead (see Pitfall 4).
Pitfall 4: projected content is created even when the slot is hidden
Placing <ng-content> inside an @if controls only whether the projected nodes are attached to the DOM. It does not control whether they are created. The parent instantiates its content when the parent view is created, so a projected component's constructor and ngOnInit run even if the slot never renders.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-collapsible',
template: `
@if (open()) {
<ng-content />
}
`,
})
export class CollapsibleComponent {
open = input(false);
}<app-collapsible [open]="false">
<app-sales-chart />
</app-collapsible>With this usage, app-sales-chart is created and initialized while the panel is closed. If it fetches data in ngOnInit, the request fires right away. Its bindings are also checked on every change detection pass of the parent.
If the content is expensive, change the API so the parent passes a template and the component decides when to create it:
import { Component, TemplateRef, contentChild, input } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
@Component({
selector: 'app-lazy-collapsible',
imports: [NgTemplateOutlet],
template: `
@if (open()) {
<ng-container [ngTemplateOutlet]="body()" />
}
`,
})
export class LazyCollapsibleComponent {
open = input(false);
body = contentChild.required(TemplateRef);
}<app-lazy-collapsible [open]="isOpen">
<ng-template>
<app-sales-chart />
</ng-template>
</app-lazy-collapsible>Now app-sales-chart is created when open() becomes true and destroyed when it becomes false. The same pattern lets one template render several times, because ngTemplateOutlet can be used in a loop.
Pitfall 5: the child's styles do not reach projected content
With the default emulated view encapsulation, Angular tags every element with an attribute tied to the component whose template declared it. Projected elements are declared in the parent's template. They carry the parent's attribute, not the host's. A style written in the host component's stylesheet therefore does not match them:
import { Component } from '@angular/core';
@Component({
selector: 'app-note',
template: `<div class="note"><ng-content /></div>`,
styles: `
/* Does NOT style projected paragraphs */
p { color: crimson; }
/* Styles the wrapper the host owns */
.note { border-left: 4px solid crimson; padding-left: 0.5rem; }
`,
})
export class NoteComponent {}The wrapper div is styled because the host component's template declares it. Paragraphs passed in by the parent are not.
Options, from most to least recommended:
- Style the wrapper the host owns and let content inherit (
color,font, and similar properties inherit through the DOM). - Expose CSS custom properties, such as
--note-accent, that the parent can set and the host's wrapper uses. - Use
:host ::ng-deep p { ... }. It works, but::ng-deepis deprecated, so treat it as a last resort.
Pitfall 6: content queries are narrower than you expect
contentChildren and contentChild find components and directives declared in the parent's template inside your host tag. Their defaults differ:
| Query | `descendants` default | What it finds by default |
|---|---|---|
| `contentChild` | `true` | The first match anywhere inside the host tag |
| `contentChildren` | `false` | Only matches that are direct children of the host tag |
A tab wrapped in a <div> inside <app-tabs> is not a direct child, so the default query does not see it. Set the option to include nested matches:
import { Component, contentChildren } from '@angular/core';
import { TabComponent } from './tab.component';
@Component({
selector: 'app-tabs',
template: `<ng-content />`,
})
export class TabsComponent {
tabs = contentChildren(TabComponent, { descendants: true });
}A related limit: a content query sees only what is written between your tags in that one template. Content that the parent puts inside another component's template is not visible, even if it ends up in the same DOM position.
Who owns what: a reference
| Concern | Owner of projected content |
|---|---|
| Creation and destruction | The parent (the template that declares the nodes) |
| Binding expressions such as `{{ value }}` and `(click)` | The parent's component class |
| Change detection | The parent's view. An `OnPush` host does not freeze it |
| Dependency injection | Follows the declaring template, not the slot position |
| Component styles | The parent's stylesheet and encapsulation |
| Position in the DOM | The host, through its `ng-content` slots |
Choosing a mechanism
Design guidelines
- Keep slots few and stable. Each slot is a public API. Two or three named slots plus a default slot is usually enough. If you need five, consider splitting the component.
- Prefer attribute selectors for slot names.
[panel-title]reads clearly and does not clash with element names. Use element selectors such asapp-tabonly when the slot holds a specific component. - Always provide a default slot or decide what happens to stray content. If you want unmatched content ignored, you cannot do that with
ng-content. Everything that reaches the host and matches no slot is dropped from the DOM when no default slot exists. Document that. - Use fallback content for optional slots, not
@ifchecks on the parent's side. The host stays simple and the parent writes less markup. - Do not put cost in projected content. If the content might never be shown, use
ng-template. - Pass data through inputs and content through slots. Do not project a
<span>whenlabel = input<string>()would do. Projection is for markup the parent shapes, and inputs are for values. - Expose styling through CSS custom properties. This avoids
::ng-deepand keeps the host's internals private. - Test with a host component. Create a small test component whose template uses your component with every slot filled, with each slot empty, and with a misspelled attribute. Rendering these cases catches routing errors that the compiler cannot.
Exercise
A component renders @if (expanded()) { <ng-content /> }. The parent projects <app-report />, which loads data in ngOnInit. With expanded() false, does the data load, and what change would delay it until the first expansion?
Show answer
Yes, the data loads. The parent creates app-report when its own view is created, whether or not the slot is rendered. To delay it, change the host to accept an <ng-template> through contentChild.required(TemplateRef) and render it with ngTemplateOutlet inside the @if. Then app-report is created only when expanded() becomes true.
Exercise
You write <app-panel><div><h2 panel-title>Settings</h2></div></app-panel>, and the title appears in the body instead of the header. Why, and name two fixes.
Show answer
select matches only the top-level nodes of the projected content. The div is the top-level node and matches no named slot, so it and the h2 inside it go to the default slot. Fixes: remove the div so the h2 is a direct child, put panel-title on the div, or wrap the content in <ng-container ngProjectAs="[panel-title]">.
Exercise
<app-tabs> uses contentChildren(TabComponent), but a <app-tab> placed inside a <div> within <app-tabs> is missing from the result. What option fixes it?
Show answer
contentChildren defaults to descendants: false, so it only finds direct children. Use contentChildren(TabComponent, { descendants: true }).