Content projection with ng-content


->Content projection is used to project content in a component
->Content projection is a way to import HTML content from outside the component and insert that content into the component’s template in a designated spot.

Why we use it?

  1. Many Components in your app using same structure and style but the content are different, in another word Reusability.
  2. You build a component for display only and the other component built for handling user actions, in another word Separation of concern.
app.component.ts
<my-component>
  Some content
</my-component>
my.component.ts
Projected content: <ng-content></ng-content>

Result Projected content: Some content

ng-content with select

app.component.ts
<my-component>
  <div class="primary">Primary content</div>
  <div secondary>Secondary content</div>
  <div>Div content</div>
  Non selected content.
</my-component>
my.component.ts
<div><ng-content></ng-content></div>
<div>
  Primary content: 
  <ng-content select=".primary"></ng-content>
</div>
<div>
  Secondary content: 
  <ng-content select="[secondary]"></ng-content>
</div>
<div>
  Div content: 
  <ng-content select="div"></ng-content>
</div>
Result
Non selected content.
Primary content:
Primary content
Secondary content:
Secondary content
Div content:
Div content

ng-content with pojectAs

You can define which selector will be used with <ng-content>.Source

app.component.ts
<my-component>
  <ng-container ngProjectAs="custom">
   Projected As.
  </ng-container>
  Non selected content.
</my-component>
my.component.ts
<div><ng-content></ng-content></div>
<div>
  <ng-content select="custom"></ng-content>
</div>

Non selected content.
Projected As.

https://dev.to/imm9o/angular-content-projection-the-complete-guide–3dcb