ng content

Overview

Angular's <ng-conent> directive is a powerful tool that enables dynamic content projection within your components. It allows you to create flexible and reusable components that can accept and display different content based on their usage. In this article, we will explore the ng-content directive, its uses, and provide hands-on examples with detailed explanations.

Understanding ng-content

<ng-content> is used for content projection, a mechanism that allows you to pass content (HTML, text, or other components) from the parent component into a child component. this is particularly useful when creating components that act as containers or layouts for various types of content.

Creating a Simple Example

Let's start with straightforward example to illustrate how ng-content works.

Parent Component (app-parent.component.html)

<app-child>
  <h1>Title</h1>
  <p>Some content to be projected into the child component.</p>
</app-child>

Child Component (app-child.component.html)

<div >
 <ng-content></ng-content>
</div>

In this example:

  • The parent component (app-parent) contains content (an h1 element and a p element) that you want to project into the child component.
  • The child component (app-child) uses <ng-content></ng-content> to define the location where the content from the parent will be inserted. In this case, the content will be inserted within a div element with the class “child-component”.

When the application is rendered, the content from the parent component is dynamically inserted into the <ng-content> element within the child component. The final rendered output will be something like this:

<div >
 <h1>Title</h1>
 <p>Some content to be projected into the child component.</p>
</div>

Transcluding Multiple Pieces of Content

You can use ng-content to transclude multiple pieces of content and specify where each piece should be inserted.

Child Component (app-child-multiple.component.html):

<div >
 <div >
  <ng-content select="header"></ng-content>
 </div>
 <div >
  <ng-content select="content"></ng-content>
 </div>
</div>

Parent Component (app-parent-multiple.component.html):

<app-child-multiple>
  <header>
    <h1>Title</h1>
  </header>
  <content>
    <p>Some content to be projected into the child component.</p>
  </content>
</app-child-multiple>

In this example, we have two named <ng-content> projections (<ng-content select="header"> and <ng-content select="content">) within the child component. The parent component provides content for these projections using <header> and <content> tags.