Angular — Four practical use cases of NgTemplateOutlet

Liu Ting Chun
5 min readApr 25, 2021

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.

Image from Evolution SKF

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>

The context is not limited to primitive types. It is possible to contain a whole object, such as a formGroup:

<ng-template #subform let-formGroup="formGroup">
<div [formGroup]="formGroup">
<div>
<label>Name</label>
<input formControlName="name">
</div>
<div>
<label>age</label>
<input formControlName="age">
</div>
<div>
<label>gender</label>
<input formControlName="gender">
</div>
</div>
</ng-template>

<div [formGroup]="receptionistForm">
<ng-container *ngTemplateOutlet="subform; context: {
formGroup: receptionistForm }"></ng-container>
<div>
<label>language</label>
<input formControlName="language">
</div>
</div>

<div [formGroup]="clerkForm">
<ng-container *ngTemplateOutlet="subform; context: {
formGroup: clerkForm }"></ng-container>
<div>
<label>typeSpeed</label>
<input formControlName="typeSpeed">
</div>
</div>
Liu Ting Chun

Web developer from Hong Kong. Most interested in Angular and Vue. Currently working on a Nuxt.js + NestJS project.

Recommended from Medium

Lists

See more recommendations