Content Projection and ‘ng-content‘ are important concepts in Angular, allowing developers to create reusable components. They enable you to pass HTML content or other Angular components from your component’s consumer (parent component) to the component itself.
**Content Projection** is a mechanism in Angular to project (or inject) the content from outside of the component into a designated part of the component’s view. It helps to create generic and reusable components.
**ng-content** is a special element in Angular that acts as a placeholder for the content that will be projected into the component. When the component is rendered, ‘ng-content‘ will be replaced with the projected content.
To better understand these concepts, let’s take a look at an example. Imagine you want to create a ‘CardComponent‘ that receives a title and some content from its parent.
Here is how the ‘CardComponent‘ would look like:
// card.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-card',
template: `
<div class="card">
<div class="card-header">
<ng-content select="[card-title]"></ng-content>
</div>
<div class="card-body">
<ng-content></ng-content>
</div>
</div>
`,
styleUrls: ['./card.component.css']
})
export class CardComponent { }
Notice how we use the ‘ng-content‘ element to designate the places where the content from the parent component will be projected. The ‘select‘ attribute is used to match specific elements from the parent component to be projected into that specific ‘ng-content‘. In this case, we are projecting elements that have a ‘card-title‘ attribute.
Now, let’s see how we can use the ‘CardComponent‘ in a parent component:
<!-- parent.component.html -->
<app-card>
<h3 card-title>Card Title</h3>
<p>This is the card content.</p>
<button>Click me!</button>
</app-card>
When the parent component renders, it will pass the content between the ‘<app-card>‘ tags to the ‘CardComponent‘. The ‘<h3>‘ element with the ‘card-title‘ attribute will be projected into the ‘ng-content‘ element with ‘select="[card-title]"`, and the rest of the elements will be projected into the ‘ng-content‘ without a ‘select‘ attribute.
So, the final rendered output of the ‘CardComponent‘ will be:
<div class="card">
<div class="card-header">
<h3>Card Title</h3>
</div>
<div class="card-body">
<p>This is the card content.</p>
<button>Click me!</button>
</div>
</div>
Content Projection and ‘ng-content‘ allow you to create flexible and reusable components in Angular by giving you control over where to insert external content within your component’s template.