ng-content lets you insert content from outside a component into specific places inside it. This helps build flexible and reusable components.
ng-content for slot-based composition in Angular
<ng-content></ng-content>
<!-- For named slots -->
<ng-content select=".slot-name"></ng-content>The plain <ng-content> tag inserts all content passed inside the component.
Using select attribute lets you create named slots to place specific content in specific spots.
<ng-content></ng-content>
header in the first slot and content with class body in the second slot.<ng-content select=".header"></ng-content> <ng-content select=".body"></ng-content>
<h1> elements in the first slot and all <p> elements in the second slot.<ng-content select="h1"></ng-content> <ng-content select="p"></ng-content>
This example shows a CardComponent with three slots: header, body, and footer. The AppComponent passes content with matching classes into each slot. The card displays the content in the right places.
import { Component } from '@angular/core'; @Component({ selector: 'app-card', template: ` <div class="card"> <div class="card-header"> <ng-content select=".header"></ng-content> </div> <div class="card-body"> <ng-content select=".body"></ng-content> </div> <div class="card-footer"> <ng-content select=".footer"></ng-content> </div> </div> `, styles: [ `.card { border: 1px solid #ccc; padding: 1rem; border-radius: 0.5rem; max-width: 300px; } .card-header { font-weight: bold; margin-bottom: 0.5rem; } .card-body { margin-bottom: 0.5rem; } .card-footer { font-size: 0.8rem; color: gray; }` ] }) export class CardComponent {} @Component({ selector: 'app-root', template: ` <app-card> <div class="header">My Card Title</div> <div class="body">This is the main content inside the card.</div> <div class="footer">Footer info here</div> </app-card> ` }) export class AppComponent {}
Content inside ng-content is projected from the parent component.
If no matching content is passed for a named slot, that slot stays empty.
You can combine multiple ng-content tags to create complex layouts.
ng-content lets you insert external content inside your component.
Use select to create named slots for different content parts.
This helps build reusable and flexible components that accept custom content.