Ankush Goyal
Posted on November 27, 2024
ng-content
is a directive in Angular that allows you to project content from a parent component into a child component. This is useful for creating reusable components that can accept dynamic content. Here's how it works:
Basic Usage
-
Child Component: Define a placeholder for the projected content using
ng-content
.
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<div class="child">
<ng-content></ng-content>
</div>
`,
styles: [`
.child {
border: 1px solid #ccc;
padding: 10px;
}
`]
})
export class ChildComponent {}
- Parent Component: Use the child component and project content into it.
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child>
<p>This content is projected into the child component.</p>
</app-child>
`
})
export class ParentComponent {}
Multiple Slots
You can also define multiple content projection slots using the select
attribute.
-
Child Component: Define multiple
ng-content
elements withselect
attributes.
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<div class="header">
<ng-content select="[header]"></ng-content>
</div>
<div class="body">
<ng-content></ng-content>
</div>
`,
styles: [`
.header {
background-color: #f1f1f1;
padding: 10px;
}
.body {
padding: 10px;
}
`]
})
export class ChildComponent {}
- Parent Component: Use the child component and project content into the specified slots.
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child>
<div header>
<h1>Header Content</h1>
</div>
<p>Body Content</p>
</app-child>
`
})
export class ParentComponent {}
Benefits of Using ng-content
- Reusability: Create flexible and reusable components that can accept different content.
- Separation of Concerns: Keep the component logic separate from the content, making it easier to manage and maintain.
- Dynamic Content: Allow dynamic content to be injected into components, enhancing the flexibility of your application.
Thank you for reading!
I hope you found this article helpful and informative. If you enjoyed it or learned something new, feel free to share your thoughts in the comments or connect with me.
If you'd like to support my work and help me create more content like this, consider buying me a coffee. Your support means the world and keeps me motivated!
Thanks again for stopping by! 😊
Posted on November 27, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.