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.
Top comments (0)