Skip to main content

ng-content

<ng-content> in Angular is a special directive used in component templates to create a content projection spot. It allows you to compose complex components by including content from outside the component. This feature is particularly useful for creating reusable and customizable components.

Concept of Content Projection

  1. Basic Idea: Content projection is the process of inserting external content into a component's view. It's similar to transclusion in AngularJS or slots in Vue.js.

  2. Use Case: It's commonly used in UI libraries and frameworks where you need a component that wraps content in a certain style or behavior, but the content itself should be defined by the user of the component.

How <ng-content> Works

  1. Defining Projection Spot: In your component's template, you define where the projected content should appear using the <ng-content> tag.

    <!-- my-wrapper.component.html -->
    <div class="wrapper-style">
    <ng-content></ng-content>
    </div>
  2. Using the Component with Projection: When you use the component, any content you include between its opening and closing tags will be projected into the <ng-content> spot.

    <!-- app.component.html -->
    <my-wrapper>
    <p>This content will be projected into the MyWrapper component.</p>
    </my-wrapper>

Selective Projection

<ng-content> can use the select attribute to project content selectively based on CSS selectors.

  1. Multiple Projection Spots: You can have multiple <ng-content> tags with different selectors.

    <!-- my-card.component.html -->
    <div class="card">
    <div class="card-header">
    <ng-content select=".card-header-content"></ng-content>
    </div>
    <div class="card-body">
    <ng-content select=".card-body-content"></ng-content>
    </div>
    </div>
  2. Projecting Specific Content: Content is projected based on the CSS class.

    <!-- app.component.html -->
    <my-card>
    <div class="card-header-content">Header</div>
    <div class="card-body-content">Body</div>
    </my-card>

    Here, the content divs are projected into their respective places in the MyCard component.

Advantages of Using <ng-content>

  • Reusability: Allows for creating generic, reusable components.
  • Customization: Users of the component can insert custom content into predefined spots.
  • Simplicity: Keeps the component API simple while allowing complex structures.

Best Practices

  • Clear Documentation: When creating components that use content projection, document clearly where and how content should be projected.
  • Avoid Overuse: Excessive content projection can make the component's structure and behavior harder to understand. Use it judiciously.