Angular ng-content Directive

The ng-content directive is used for content projection. the main work is used for inserting external or dynamic content. The Parent component passes the external content into the child component.

Suppose You created an automobile component through the below command.


ng g c automobile

Now, put the code into automobile.component.html file


<div>
  <h3 class="title">Maruti</h3>
  <div>Lorem Ipsum is simply dummy</div>
  <h4 class="rank">Rank 1</h4>
</div>

Now, include automobile component into app.component.html file


<div class="text-center" role="main">
<h2>AutoMobiles Industries</h2>
<div class="row">

<div class="col-md-4">
<app-automobile></automobile>
</div>

<div class="col-md-4">
<app-automobile></automobile>
</div>

<div class="col-md-4">
<app-automobile></automobile>
</div>

</div>
</div>


Now, in the above picture, all items are the same so now we are going to create a title for each section.

instead of the title, add ng-content into the automobile.component.html file and we do add title under the app-automobile into the app.component.html file


<div>
  <ng-content></ng-content>
  <div>Lorem Ipsum is simply dummy</div>
  <h4 class="rank">Rank 1</h4>
</div>

app.component.html file


<div class="text-center" role="main">
<h2>AutoMobiles Industries</h2>
<div class="row">

<div class="col-md-4">
<app-automobile>
 <h3 class="title">Maruti</h3>
</automobile>
</div>

<div class="col-md-4">
<app-automobile>
 <h3 class="title">Tata</h3>
</automobile>
</div>

<div class="col-md-4">
<app-automobile>
 <h3 class="title">Mahindra</h3>
</automobile>
</div>

</div>
</div>

ng-content used in more than one times in child component

Suppose, You want to add more than one ng-content into a child component then you have to make it unique through select keyword in the ng-content.

Suppose, You want to create a Rank dynamic

instead of the Rank, add ng-content into the automobile.component.html file and we do add Rank under the app-automobile into the app.component.html file


<div>
  <ng-content  select=".title"></ng-content>
  <div>Lorem Ipsum is simply dummy</div>
  <ng-content select=".rank"></ng-content>
</div>

app.component.html file


<div class="text-center" role="main">
<h2>AutoMobiles Industries</h2>
<div class="row">

<div class="col-md-4">
<app-automobile>
 <h3 class="title">Maruti</h3>
 <h4 class="rank">Rank 1</h4>
</automobile>
</div>

<div class="col-md-4">
<app-automobile>
 <h3 class="title">Tata</h3>
<h4 class="rank">Rank 1</h4>
</automobile>
</div>

<div class="col-md-4">
<app-automobile>
 <h3 class="title">Mahindra</h3>
<h4 class="rank">Rank 1</h4>
</automobile>
</div>

</div>
</div>