Content projection is a pattern in which you insert the content that you want to show inside another component.
<ng-content></ng-content>
- responsible to project content inside another component. It is just a placeholder and will be replaced by actual projected content.
There are several ways of doing this in Angular:
- Single-slot content projection: other component accepts content from single source
<!--app.component.html--> <app-child> <p>project this content</p> </app-child> <!--child.component.html--> <p>Single-slot content projection</p> <ng-content></ng-content>
output:
- Multi-slot content projection: Component accepts content from multiple sources. Hence, we must specify where to project content. We can accomplish this task by
select
attribute of<ng-content>
<!--app.component.html--> <app-child> <p> First project content </p> <p select="[foo]"> foo project content </p> <p select="[bar]"> bar project content </p> <p> Lastly projected content </p> </app-child> <!--child.component.html--> <h2>Multi-slot content projection</h2> <ng-content></ng-content> <ng-content #foo></ng-content> <ng-content #bar></ng-content>
output:
Note: An element without a select attribute receives all projected components that do not match any of the other elements.
- If you observe above the
Lastly projected content
doesn't have anyselect
but still projected via emptyng-content
.
- Conditional Content Projection: Achieved using
<ng-template>
andngTemplateOutlet
directive.
<h2>Conditional Content Projection</h2> <p>Basic Template outlet Implementation</p> <ng-template #template1> <p>template info</p> </ng-template> <p>It prints before templateInfo</p> <ng-container *ngTemplateOutlet="template1"> </ng-container>
ngTemplateOutlet
is a structural directive used to insert ng-template
in various sections of DOM.
User can use any element like div. But div won't be rendered
<div *ngTemplateOutlet="template1"></div>
Output:
We can also pass value to ngTemplateOutlet
using ngTemplateOutletContext
property.
<p>Passing value to template outlet</p> <ng-template let-value="value" #template2> <p>Value recieved: {{ value }}</p> </ng-template> <ng-container [ngTemplateOutlet]="template2" [ngTemplateOutletContext]="{ value: 100 }" > </ng-container> <!--Alternatively--> <ng-container *ngTemplateOutlet="template2; context: { value: 100 }" ></ng-container>
We can also send multiple values.
Output:
You can view the complete output here:
Please let me know if I miss to cover any cases.
You can follow me: https://twitter.com/urstrulyvishwak
Thanks
Top comments (0)