Key Takeaways
<ng-content>allows you to create components with dynamic content by leveraging Angular's content projection.- You can use the
selectattribute to project different sections of content into a component, based on HTML selectors. - Styling projected content may require global styles or
:hostwith careful management.
Understanding <ng-content> in Angular
The <ng-content> directive in Angular unleashes the power of templates to include dynamic content within your components. It enables you to define how content is injected into a component, supporting reusable designs.
Basic <ng-content> Example
my-button.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-button',
template: `
<button class='action-btn' (click)="action()">
<ng-content></ng-content>
</button>
`
})
export class MyButtonComponent {
action() {
console.log("action triggered");
}
}
app.component.html
<my-button>Click Me!</my-button>
<my-button>Press Here!</my-button>
Here, <ng-content> is used to insert button labels dynamically, making the my-button component flexible for various labels without modifying the component itself.
Multiple Content Projections
contact.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'contact',
template: `
<div class='contact'>
<ng-content select="h1"></ng-content>
<ng-content select=".phone"></ng-content>
<ng-content></ng-content>
</div>
`
})
export class ContactComponent {}
app.component.html
<contact>
<h1>John</h1>
<span class="phone">555-433-3322</span>
<p>John is a coworker.</p>
</contact>
<contact>
<h1>Jane</h1>
<span class="phone">555-334-1123</span>
<p>Jane is a friend.</p>
</contact>
Using the select attribute, you can direct specific contents to specified projection slots based on structural CSS selectors like tags or custom classes. Remaining elements are projected to the non-specified, catch-all <ng-content> slot.
Styling Projected Content
Styling content projected via <ng-content> can be tricky, as styles might not apply directly due to encapsulation.
contact.component.css
:host ::ng-deep .phone {
color: red;
}
:host ::ng-deep allows you to pierce component encapsulation, which is useful for applying styles to deeply nested elements. Note that ::ng-deep may eventually be deprecated, so plan for alternatives like global styles or CSS variables.
FAQ
What is the purpose of <ng-content> in Angular?
The <ng-content> directive is used for content projection, allowing you to insert custom content into a component's template, enhancing flexibility and reusability.
Can I have multiple <ng-content> tags in a component?
Yes, you can use multiple <ng-content> tags with the select attribute to manage different projections based on given selectors.
How can I style content within <ng-content>?
Styling projected content involves either using :host ::ng-deep, although deprecated, or by applying styles in a global context or through carefully managed CSS properties or variables.
