Sitemap
Press enter or click to view image in full size
Angular: How to project content

Content projection is a good way to reuse a component for different scenarios where only the content of the component changes but the functionality remains the same.

Let’s take an example of add and update product form where the functionality remains the same, but only the title will change based on the add or edit the product. so this is where we can utilize the angular content projection feature to change the content in the product add/edit component and reuse the same component for add and edit use case.

Get ✨Muhammad Sohail Nazar’s stories in your inbox

Join Medium for free to get updates from this writer.

So we will start from our app component where we‘ll use “app-product-form. component” twice. to reproduce this scenario.

Press enter or click to view image in full size

In the first use case, we‘ll pass the “Add Product” heading in the h3 tag inside our “app-product-form”.
to handle the second use case. we‘ll pass the “Edit Product” heading in the h3 tag inside our “app-product-form”.

Press enter or click to view image in full size

To render the h3 heading in the “app-product-form” component. we‘ll use <ng-content>, and it will render whatever content is passed from the parent while using this component.

--

--

✨Muhammad Sohail Nazar
✨Muhammad Sohail Nazar

Written by ✨Muhammad Sohail Nazar

Senior Software Engineer with 8+ years of expertise in .NET Core, Angular, and React. Passionate about building scalable, reliable apps using Agile and DDD.