Content Projection in Angular: A Quick Guide
Introduction
Content projection in Angular allows you to pass content from a parent component into a child component, making components more flexible and reusable. This is done using the <ng-content>
directive.
In this article, we'll explore a simple example, a more advanced use case, and wrap up with key takeaways.
Basic Example
Let's assume we want to display a confirmation message in a component, and the message would be customizable.
<!-- Confirmation component (app-confirmation) -->
<div>
<h1>Confirmation</h1>
<ng-content />
<div class="footer">
<button (click)="confirmAction()">Confirm</button>
</div>
</div>
<!-- Parent component -->
<app-confirmation>
<p> Do you want to confirm this action? </p> <!-- This will be projected in the ng-content slot -->
</app-confirmation>
Advanced Example: Multi-slot Projection
Let's take the same confirmation component, but now we also want to display a custom footer.
<!-- Confirmation component (app-confirmation) -->
<div>
<h1>Confirmation</h1>
<ng-content select="body"/>
<div class="footer">
<ng-content select="footer" />
</div>
</div>
<!-- Parent component -->
<app-confirmation>
<body>
<p> Do you want to confirm this action? </p>
</body>
<footer>
<button (click)="cancel()">Cancel</button>
<button (click)="confirmAction()">Confirm</button>
</footer>
</app-confirmation>
Here I used body
and footer
, but you could select elements by CSS class, attribute name, or anything you like.
Conclusion
Content projection is a powerful feature that makes Angular components more reusable and dynamic. Whether you need simple or multi-slot projection, <ng-content>
helps you create highly flexible components.
Additionally, for even more flexibility, you can use ngTemplateOutlet to dynamically render templates based on conditions or external inputs, allowing for advanced component customization.