DEV Community

Ankush Goyal
Ankush Goyal

Posted on

ng-content in Angular

ng-content is a directive in Angular that allows you to project content from a parent component into a child component. This is useful for creating reusable components that can accept dynamic content. Here's how it works:

Basic Usage

  1. Child Component: Define a placeholder for the projected content using ng-content.
   import { Component } from '@angular/core';

   @Component({
     selector: 'app-child',
     template: `
       <div class="child">
         <ng-content></ng-content>
       </div>
     `,
     styles: [`
       .child {
         border: 1px solid #ccc;
         padding: 10px;
       }
     `]
   })
   export class ChildComponent {}
Enter fullscreen mode Exit fullscreen mode
  1. Parent Component: Use the child component and project content into it.
   import { Component } from '@angular/core';

   @Component({
     selector: 'app-parent',
     template: `
       <app-child>
         <p>This content is projected into the child component.</p>
       </app-child>
     `
   })
   export class ParentComponent {}
Enter fullscreen mode Exit fullscreen mode

Multiple Slots

You can also define multiple content projection slots using the select attribute.

  1. Child Component: Define multiple ng-content elements with select attributes.
   import { Component } from '@angular/core';

   @Component({
     selector: 'app-child',
     template: `
       <div class="header">
         <ng-content select="[header]"></ng-content>
       </div>
       <div class="body">
         <ng-content></ng-content>
       </div>
     `,
     styles: [`
       .header {
         background-color: #f1f1f1;
         padding: 10px;
       }
       .body {
         padding: 10px;
       }
     `]
   })
   export class ChildComponent {}
Enter fullscreen mode Exit fullscreen mode
  1. Parent Component: Use the child component and project content into the specified slots.
   import { Component } from '@angular/core';

   @Component({
     selector: 'app-parent',
     template: `
       <app-child>
         <div header>
           <h1>Header Content</h1>
         </div>
         <p>Body Content</p>
       </app-child>
     `
   })
   export class ParentComponent {}
Enter fullscreen mode Exit fullscreen mode

Benefits of Using ng-content

  • Reusability: Create flexible and reusable components that can accept different content.
  • Separation of Concerns: Keep the component logic separate from the content, making it easier to manage and maintain.
  • Dynamic Content: Allow dynamic content to be injected into components, enhancing the flexibility of your application.

Top comments (0)