Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 74 ยท Components in Depth

Content Projection

Learn Angular content projection - ng-content slots, select, ngProjectAs, ng-container, and ng-template with ngTemplateOutlet - with runnable stand-ins.

A reusable component often needs to wrap content that its user provides: a card with a title and some body text, a dialog with its own buttons, a tab panel with whatever the page puts inside it. If the component had to receive all of that through inputs, it would turn into a pile of strings and flags. Content projection solves this: the parent writes markup between the component's tags, and the component decides where that markup shows up inside its own template.

In Angular, the place where projected content lands is marked with <ng-content>. This lesson covers a single slot, multiple named slots with select, grouping with <ng-container>, and the more flexible <ng-template> plus ngTemplateOutlet when plain projection is not enough. It builds on Inputs and Outputs: inputs pass data, projection passes markup.

What is real and what is a stand-in. The typescript and html code blocks that show Angular components and templates are real Angular, but this site cannot run the Angular compiler, so they are read-only. The runnable examples are small stand-ins written in plain TypeScript and JavaScript that re-implement the idea of slot matching so you can experiment with it. They are not Angular's code.

A single slot

Here is a card component with one slot. Whatever the parent puts between <app-card> and </app-card> replaces <ng-content />:

TypeScript
import { Component } from '@angular/core';

@Component({
  selector: 'app-card',
  template: `
    <article class="card">
      <ng-content />
    </article>
  `,
  styles: `.card { border: 1px solid #ccc; padding: 1rem; border-radius: 8px; }`,
})
export class CardComponent {}
HTML
<app-card>
  <h2>Welcome</h2>
  <p>This markup is written by the parent, shown inside the card.</p>
</app-card>

The h2 and p belong to the parent's template. They are created by the parent, bound to the parent's data, and styled by the parent's encapsulated styles. The card only decides where to put them. That is an important difference from a child component's own template, and it explains several behaviors later in this lesson. Component tags can be self-closing in templates, so <ng-content /> and <ng-content></ng-content> mean the same thing.

flowchart LR
  P["Parent template<br/>(writes the markup)"] --> C["app-card<br/>(owns the layout)"]
  P -->|"h2, p"| S["ng-content slot<br/>inside the card"]
  C --> S

The parent supplies the nodes; the card decides where the slot sits.

Multiple slots with select

A card usually needs more than one place: a header, a body and a footer. Add several <ng-content> elements and give all but one a select attribute. The value is a CSS selector (an element name, a class, an attribute, or a comma-separated list of those). Each child of the component is matched against the selectors:

TypeScript
@Component({
  selector: 'app-panel',
  template: `
    <section class="panel">
      <header><ng-content select="[panel-title]" /></header>
      <div class="body"><ng-content /></div>
      <footer><ng-content select="button, .panel-actions" /></footer>
    </section>
  `,
})
export class PanelComponent {}
HTML
<app-panel>
  <h3 panel-title>Storage</h3>
  <p>You have used 80% of your space.</p>
  <button type="button">Upgrade</button>
</app-panel>

The h3 has a panel-title attribute, so it goes to the header. The button matches the footer selector. The p matches nothing specific, so it ends up in the default slot, the <ng-content> without select. If there were no default slot, unmatched content would simply be dropped.

Some details worth knowing:

  • Matching looks at the content's top-level nodes only, not at their descendants. A button nested inside a div is not matched on its own; the div is.
  • Slots do not have to be listed in the same order as the content. The component's template decides the final order.
  • Since Angular 18, <ng-content> can contain fallback content that is shown when nothing is projected into that slot, for example <ng-content select="[panel-title]">Untitled</ng-content>.
  • Projected nodes are created once, by the parent. You cannot clone them into two slots. If two <ng-content> elements can match the same node, only one of them receives it.

Try the matching rules yourself with this stand-in. It models the parent's children as plain objects and each slot as a selector, then distributes the children the way the real feature does (specific selectors first, everything else to the default slot).

TypeScript Stand-in: distributing nodes into slots

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first part prints each slot with its nodes in the order the parent wrote them. In the second part there is no default slot, so both paragraphs are reported as dropped. That is the "unmatched content disappears" rule in action.

ngProjectAs and ng-container

Sometimes you want to project several elements into one slot, or you want to project something whose real tag does not match the slot. Wrapping everything in a div would add a needless element to the DOM. <ng-container> is a grouping element that renders nothing itself: only its children reach the DOM.

The catch is that select matches the ng-container itself, and an ng-container has no attributes of its own that mean anything. The ngProjectAs attribute fixes that. It tells Angular "match me as if I were this selector":

HTML
<app-panel>
  <ng-container ngProjectAs="[panel-title]">
    <h3>Storage</h3>
    <small>Plan: Pro</small>
  </ng-container>
  <p>You have used 80% of your space.</p>
</app-panel>

Both the h3 and the small land in the header slot, with no wrapper element. ngProjectAs takes one selector only (a single element, attribute or class selector, not a comma list), and it is a plain attribute, not a binding.

Content is created even when the slot is hidden

A common surprise: putting <ng-content> inside an @if does not stop the content from being created.

TypeScript
@Component({
  selector: 'app-collapsible',
  template: `
    <button type="button" (click)="open.set(!open())">Toggle</button>
    @if (open()) {
      <ng-content />
    }
  `,
})
export class CollapsibleComponent {
  open = signal(false);
}

The parent creates its projected children (and runs their constructors, ngOnInit, and so on) as soon as the app-collapsible tag is created, whether or not the slot is rendered. The @if only decides whether those existing nodes are attached to the page. If the projected content is expensive, or fetches data when it starts, that matters. When you need content to be created lazily, pass a template instead of nodes.

ng-template and ngTemplateOutlet

An <ng-template> is a blueprint: Angular compiles it but does not render it until someone instantiates it. ngTemplateOutlet is the directive that instantiates a template at a given place, optionally with a context of values for the template to use:

TypeScript
import { Component, TemplateRef, contentChild, input } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';

@Component({
  selector: 'app-list',
  imports: [NgTemplateOutlet],
  template: `
    <ul>
      @for (item of items(); track item) {
        <li>
          <ng-container
            [ngTemplateOutlet]="rowTemplate() ?? defaultRow"
            [ngTemplateOutletContext]="{ $implicit: item, index: $index }"
          />
        </li>
      }
    </ul>

    <ng-template #defaultRow let-item>{{ item }}</ng-template>
  `,
})
export class ListComponent {
  items = input.required<string[]>();
  rowTemplate = contentChild<TemplateRef<unknown>>('row');
}
HTML
<app-list [items]="['Ada', 'Grace', 'Linus']">
  <ng-template #row let-person let-i="index">
    {{ i + 1 }}. <strong>{{ person }}</strong>
  </ng-template>
</app-list>

Here the list component owns the loop and the layout, while the parent decides how each row looks. let-person binds to the context's $implicit value, and let-i="index" binds to the index key. If the parent gives no template, the list falls back to defaultRow. The template is rendered once per item, and only when the outlet runs, so unlike plain <ng-content> it can render zero, one or many times. View queries such as contentChild are covered in the next lesson but one.

flowchart TD
  T["ng-template #row<br/>(blueprint from the parent)"] --> O["ngTemplateOutlet<br/>(inside app-list)"]
  X["context: item, index"] --> O
  O --> V1["row view 1"]
  O --> V2["row view 2"]
  O --> V3["row view 3"]

One template, instantiated once per item with a different context each time.

Here is a stand-in for that mechanism. A "template" is just a function from a context to a string, and the outlet calls it for each item.

TypeScript Stand-in: a template outlet with context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice that the same renderList serves strings and objects: the list is generic and the row appearance belongs to the caller, which is the whole point of passing a template.

Seeing slots in a page

This last example uses plain JavaScript and real DOM nodes to build a card from a blueprint and fill its slots. Press the button to change what the "parent" projects. It is a stand-in for what Angular does at compile time and render time.

Stand-in: a card with header, body and footer slots

The second variant has no footer content, so the card keeps its fallback text. In Angular you would write that fallback inside the <ng-content select="..."> element.

Which tool when?

  • Use plain <ng-content> when the parent supplies static markup that the component only needs to place: wrappers, cards, layout shells.
  • Add select when the component has more than one place to fill.
  • Use ngProjectAs with <ng-container> when one slot should receive several nodes, or a node with the wrong tag.
  • Use ng-template with ngTemplateOutlet when the component must decide when and how often to render the content, or must pass data to it (row templates, empty states, custom headers).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A component's template has <ng-content select="[title]" /> and <ng-content />. Where does a <p> without attributes go?

    Content is matched against the specific selectors first. Anything that matches none of them goes to the default <ng-content>.
  2. 2. You place <ng-content /> inside @if (open()). While open() is false, what happens to the projected content?

    The parent creates projected content eagerly. The @if only decides whether the existing nodes are attached. For lazy content, pass an ng-template and render it with ngTemplateOutlet.
  3. 3. What is ngProjectAs for?

    ngProjectAs="[panel-title]" makes the node count as matching that selector, so grouped content can reach a slot without a wrapper element.
  4. 4. In let-person on an ng-template used with ngTemplateOutlet, which context key does person receive?

    A bare let-name binds to the context's $implicit property. Other keys need let-x="key".

Summary

  • <ng-content> marks where the parent's markup appears inside a component. The parent creates that content, so its bindings and styles belong to the parent.
  • select takes a CSS selector, so one component can have several slots. Unmatched content goes to the default slot, or is dropped when there is none. Fallback content for an empty slot is supported since Angular 18.
  • <ng-container> groups nodes without adding an element, and ngProjectAs lets the group match a slot's selector.
  • Projected content is created eagerly, even if its slot sits in an @if that is false.
  • ng-template plus ngTemplateOutlet (with a context) gives the component control over when and how often content renders.

Next: Lifecycle Hooks and afterNextRender