Angular content projection using ngContent directiveby Sai gowtham2min read
In this tutorial, we are going to learn about how to project content into components by using ngContent directive.
In angular ng-content directive helps to project data into particular places of a component.
Let’s see an example:
<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.
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.
<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>
Sometimes we need to pass the data in multiple places in such cases we need to target the data by using
element name or
<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.
<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>