In the previous article on this topic, I touched the basics of Content Projection with Angular and how easily one can work with dynamic templates without much fuss. I also discussed the use case where one may need to project content to a Component dynamically.
Continuing in this post, I will touch some advanced use case scenarios where we can leverage the power that Angular provides.
Now, to discuss further, a Component provides us a functionality where we may pass the template in between the opening and closing braces of the component where we use it as a child in our template.
Like <demo><h1>This is the template for content projection</h1></demo>
The contents of the <h1>
tag will be displayed where <ng-content>
tag is present in the child i.e., demo component.
What if the child has several <ng-content>
tags. How can we pass the template to a particular <ng-content>
tag thereby rendering the dynamic view to its correct position?
Let's discuss Targeted Projection.
Angular provides us with the select
attribute of the ng-content
tag. With this attribute, we can actually work with targeted projection.
Use case 1:
<ng-content select="[first-place]"></ng-content>
The template can be passed as follows:
<demo>
<p first-place>Hello World!</p>
</demo>
Use case 2:
<ng-content select="[place='first']"></ng-content>
<ng-content select="[place='second']"></ng-content>
The template can be passed as follows:
<demo>
<p place='first'>Content 1</p>
<p place='second'>Content 2</p>
</demo>
Use case 3:
<ng-content select=".place-first"></ng-content>
<ng-content select=".place-second"></ng-content>
The template can be passed as follows:
<demo>
<p class='place-first'>Content 1</p>
<p class='place-second'>Content 2</p>
</demo>
There are a few other use cases as well, which I will keep for some other day to discuss. I hope this post proves to be useful in you Angular learning journey. Cheers!
Top comments (1)
If you like content projection you will love ngtemplateoutlets!