liveBook · Manning

Ng-content

As explained in Pro Angular 16

ng-content is Angular template syntax that marks where a component's host-element content is projected into its template.

`ng-content` marks where a component’s template includes content placed inside its host element. Angular replaces the marker with that content. This lets a component provide a wrapper without knowing what the host contains. section 16.2.2

A toggleable wrapper

A toggle component puts a checkbox in its template and applies `*ngIf="showContent"` to `<ng-content>`. Its host element contains a product-table component, so the checkbox controls whether the table is displayed. 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>

See where the checkbox and projection point sit in the wrapper template. section 16.2.2

Listing 16.21. Adding a host element with Content in the template.html file in the src/app folder
<div class="container-fluid">
    <div class="row p-2">
        <div class="col-4 p-2 text-dark">
            <paProductForm (paNewProduct)="addProduct($event)">
            </paProductForm>
        </div>
        <div class="col p-2">
            <paToggleView>
                <paProductTable [model]="model"></paProductTable>
            </paToggleView>            
        </div>
    </div>
</div>

See the product table placed inside the wrapper’s host element. section 16.2.2

How Pro Angular 16 covers it

How deep it goes
Defines the projection point and demonstrates one checkbox-controlled use of it.
Examples
Wraps a product-table component in a toggle component whose checkbox controls its visibility.
What it assumes
Assumes familiarity with components and templates while defining content projection through a host-element example.
What you can do after
Apply it via Angular templates to include host content in a component and control its visibility with `*ngIf`.
How it connects
Connects component templates and host elements with content projection, `*ngIf`, and `ngModel`.

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.