Angular Content Projection is a technique where content is projected in components. By using content projection, we can reuse component's html in another component.

In Content Projection, We define some content in parent component and use <ng-content> in child component for projection.



ng-content

ng-content is use in child component to project content. Lets create a component card for projection.

ng g c card

Create component card

Create a component card and import in app component and import in app component.

           <!--app.component.ts-->
import { Component } from '@angular/core';
import { CardComponent } from "./card/card.component";

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ CardComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
  
})

export class AppComponent {
  title = 'myApp';
}

Create content for projection in parent component

To project content, create <app-card> in parent component with a h2 and paragraph element.

           <!--app.component.html-->
  <h1>{{title}}</h1>
  
  <app-card>
    <h2>Card Heading</h2>
    <p>Card Paragraph</p>
  </app-card>

Project content in child component

ng-content will project <app-card> html from parent component to child component.

           <!--card.component.html-->

    <ng-content></ng-content>


Multi Slot Projection

Multi Slot Projection is where we project individual element, class, id or attribute in multiple ng-content in child component. For Multi Slot Projections, we can use selectors like

Selectors

  1. Type or Element Selector
  2. Class Selector
  3. Id Selector
  4. Attribute Selector

App Component

           <!--app.component.ts-->
import { Component } from '@angular/core';
import { CardComponent } from "./card/card.component";

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ CardComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
  
})

export class AppComponent {
  title = 'myApp';
}

Create content for projection in parent component

<app-card> in parent component has heading, paragraph and a footer.

           <!--app.component.html-->
  <h1>{{title}}</h1>
  
  <app-card>
    <h2>Card Heading</h2>
    <p>Card Paragraph</p>
    <footer>Card Footer</footer>
  </app-card>

Project content in child component

ng-content with select="h2" wil project h2 only. To project paragraph in another ng-content, use code select="p".

           <!--card.component.html-->

    <ng-content select="h2"></ng-content>
    <ng-content select="p"></ng-content>

Project Class, Id and Attribute

ng-content with select=".sub" wil project sub class, ng-content with select="#active" will project id active and ng-content with select="[title]" will project element with title attribute only.

           <!--card.component.html-->

    <ng-content select=".sub"></ng-content>
    <ng-content select="#active"></ng-content>
    <ng-content select="[title]"></ng-content>