liveBook · Manning

Content projection

As explained in Pro Angular 16

Content projection is an Angular technique that inserts content from a component's host element into the component's template.

Content projection places content written inside a component’s host element into that component’s template. Add `<ng-content>` where the host content should appear. This lets a component provide a wrapper without knowing what the wrapper contains. section 16.2.2

A toggleable product table

A toggle component defines `showContent = true`. Its template binds a checkbox to that property and places `*ngIf="showContent"` on `<ng-content>`. Used as `<paToggleView><paProductTable [model]="model"></paProductTable></paToggleView>`, it lets the checkbox control whether the table is visible. Register the toggle component in the Angular module before using it. section 16.2.2

Listing 16.19. The contents of the toggleView.component.html file in the src/app folder
<div class="form-check"> 
    <label class="form-check-label">Show Content</label>
    <input class="form-check-input" type="checkbox"
        [(ngModel)]="showContent" />
</div>
<ng-content *ngIf="showContent"></ng-content>

The template shows the checkbox and the projection point together: `ng-content` is where Angular inserts the host element’s content. section 16.2.2

How Pro Angular 16 covers it

How deep it goes
Works through a registered toggle component and its template, but stops short of projection internals.
Examples
Uses a checkbox-controlled wrapper around a product table, with component, template, registration, and host-element listings.
What it assumes
Assumes basic Angular components and templates while defining content projection through a concrete implementation.
What you can do after
Build it from scratch as a component that conditionally displays content supplied inside its host element.
How it connects
Connects component templates, host elements, `ng-content`, `ngIf`, and checkbox data binding.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.