by Sai gowtham

Angular content projection using ngContent directive

In this tutorial, we are going to learn about how to project content into components by using ngContent directive.

ng-content

In angular ng-content directive helps to project data into particular places of a component.

Let’s see an example:

my-component.component.html
<div>
   <h1>This component uses ngContent</h1>
    <ng-content></ng-content></div>

In the above code, we have added a ng-content as an HTML tag.

Projecting the data

Now we are passing the data in between <app-my-component> opening and closing </app-my-component> tags so that <ng-content></ng-content> is replaced by the data we are passing.

app.component.html
<div>
    <h1>I'm from app component</h1>
    <app-my-component>        <p>This is some random words which are added        in the place of ng-content</p>    </app-my-component></div>

ngcontent-example-angular

Projecting the data in multiple places

Sometimes we need to pass the data in multiple places in such cases we need to target the data by using class name, element name or attribute names.

my-component.component.html
<div>
  <ng-content select=".post-title"></ng-content>
  <ng-content select=".post-body"></ng-content>
</div>

Here we are targeting data using class names so that we need to pass the data by using the above class names.

app.component.html
<div>
    <h1>I'm from app component</h1>
    <app-my-component>
        <h1 class="post-title">My first post</h1>        <p class="post-body">            My post explains about ng-content
        </p>
    </app-my-component>
</div>

ngcontent-multiple-projections

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course