Projection
Projection is a very important concept in Angular. It enables developers to build reusable components and make applications more scalable and flexible. To illustrate that, suppose we have a ChildComponent like:
@Component({ selector: 'rio-child', template: `
Child Component
{{ childContent }} ` }) export class ChildComponent { childContent = "Default content"; }What should we do if we want to replace {{ childContent }} to any HTML that provided to ChildComponent? One tempting idea is to define an @Input containing the text, but what if you wanted to provide styled HTML, or other components? Trying to handle this with an @Input can get messy quickly, and this is where content projection comes in. Components by default support projection, and you can use the ngContent directive to place the projected content in your template.
So, change ChildComponent to use projection:
app/child/child.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'rio-child', template: `
Child Component
Then, when we use ChildComponent in the template:
app/app.component.html
...... My projected content.
This is telling Angular, that for any markup that appears between the opening and closing tag of
When doing this, we can have other components, markup, etc projected here and the ChildComponent does not need to know about or care what is being provided.
View Example
But what if we have multiple
app/child-select.component.html
Child Component with Select
Then in the template, we can use directives, say,
app/app.component.html
...... Section Content p with .class-select
Header Content
Besides using directives, developers can also select a ng-content through css class:
app/app.component.html
p with .class-select
View Example