Angular — Four practical use cases of NgTemplateOutlet
NgTemplateOutlet
is one of the most overlooked features in Angular. In fact, it is designed to cater some very specific scenario that alternative is hardly found. It can highly improve the code quality when used correctly. Here I have summarized four practical use cases of NgTemplateOutlet
that can fit in many projects.
1. Create reusable HTML blocks
The most intuitive way to use NgTemplateOutlet
is to handle shared HTML codes. It works very similar to an anonymous function, but for HTML instead of JavaScript.
<ng-template #testTemplate>
<div>Some Code.</div>
</ng-template>
<ng-container *ngTemplateOutlet="testTemplate"></ng-container>
<ng-container *ngTemplateOutlet="testTemplate"></ng-container>
We can put the shared HTML inside a <ng-template>
and “call” it with NgTemplateOutlet
. It sounds pretty useless at this point. Yet, the true power comes from its ability to have context, in other words, “parameters”.
<ng-template #testTemplate let-name="name">
<div>My name is {{name}}.</div>
</ng-template>
<ng-container *ngTemplateOutlet="testTemplate; context: { name: 'John' }"></ng-container>
<ng-container *ngTemplateOutlet="testTemplate; context: { name: 'Jenny' }"></ng-container>