0
0
AngularConceptBeginner · 3 min read

What is ng-content in Angular: Explained with Examples

ng-content in Angular is a way to insert external content into a component's template. It acts like a placeholder that lets you project content from a parent component into a child component's view.
⚙️

How It Works

Imagine you have a gift box (a component) and you want to put different gifts (content) inside it each time you give it to someone. ng-content is like the empty space inside the box where you place those gifts. It allows the component to display whatever content is passed from outside.

When Angular renders the component, it replaces the ng-content tag with the content provided between the component's opening and closing tags. This process is called content projection. It helps create reusable components that can display different content without changing their internal structure.

💻

Example

This example shows a simple card component that uses ng-content to display any content passed to it.

typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-card',
  template: `
    <div style="border: 1px solid #ccc; padding: 1rem; border-radius: 0.5rem; max-width: 300px;">
      <ng-content></ng-content>
    </div>
  `
})
export class CardComponent {}

@Component({
  selector: 'app-root',
  template: `
    <app-card>
      <h2>Welcome!</h2>
      <p>This is content inside the card.</p>
    </app-card>
  `
})
export class AppComponent {}
Output
<div style="border: 1px solid #ccc; padding: 1rem; border-radius: 0.5rem; max-width: 300px;"><h2>Welcome!</h2><p>This is content inside the card.</p></div>
🎯

When to Use

Use ng-content when you want to create flexible, reusable components that can display different content depending on where they are used. It is especially useful for layout components like cards, modals, tabs, or buttons that need to wrap or decorate content provided by their parent.

For example, a modal component can use ng-content to show any message or form inside it without knowing the details in advance. This keeps components simple and focused on structure, while letting the parent control the content.

Key Points

  • ng-content is a placeholder for external content inside a component.
  • It enables content projection, letting parent components insert HTML into child components.
  • Helps build reusable and flexible UI components.
  • Supports multiple ng-content tags with selectors for advanced use cases.

Key Takeaways

ng-content allows components to display content passed from their parent.
It works by projecting external content into a component's template placeholder.
Use it to create reusable components that can wrap or decorate different content.
Content projection keeps components flexible and focused on layout, not content.
Multiple ng-content tags can be used for complex content insertion.