Enhancing Angular Component Flexibility with Fallback Content in ng-content
Angular developers have long sought after a feature that enhances the flexibility and robustness of components, and with Angular v18, their prayers have been answered: the introduction of fallback content for ng-content
slots. This eagerly anticipated feature empowers developers to specify default content to be displayed if no projected content is provided within an ng-content
slot:
@Component({
selector: 'my-comp',
template: `
<ng-content select="header">Default header</ng-content>
<ng-content>Default main content</ng-content>
<ng-content select="footer">Default footer</ng-content>
`
})
export class MyComponent {}
In the example above, we define a component MyComponent
with multiple ng-content
slots for header, main content, and footer. By providing default content within each ng-content
tag, we ensure that if no content is projected into these slots, the specified default content will be displayed.
Consider the usage of this component in another component:
@Component({
template: `
<my-comp>
Custom main content
<footer>New footer</footer>
</my-comp>
`
})
class AppComponent {}
Here, within the AppComponent
, we project custom main content and a new footer into MyComponent
. Since no content is projected into the header slot, the default header specified within the MyComponent
template will be displayed. Similarly, if no content is projected into the main content slot, the default main content will be used.
It’s important to note that Angular’s content projection occurs during creation time. This means that dynamically changing the contents of a slot, for example, through conditional rendering, will not cause the default content to be displayed.
@Component({
selector: 'my-comp',
template: `
<ng-content select="header">Default header</ng-content>
<ng-content>Default main content</ng-content>
<ng-content select="footer">Default footer</ng-content>
`
})
export class MyComponent {}
@Component({
template: `
<my-comp>
@if(condition) {
Custom main content
}
<footer>New footer</footer>
</my-comp>
`
})
class AppComponent {}
In the above example, even though there’s conditional rendering of the main content, it will not fall back to the default content because such dynamic changes are not considered during Angular’s content projection.
🙏 Support ngneat & Netanel Basal: Get Featured!
Are you passionate about the ngneat open source libraries for Angular or find Netanel Basal’s blog posts invaluable for your learning journey? Show your support by sponsoring my work!
Follow me on Medium or Twitter to read more about Angular and JS!