Member-only story

Angular — Communicating between templates with function-like HTML segments

Liu Ting Chun
5 min readOct 15, 2020

--

The function-like HTML segment refers to a block of HTML with the ability to accept context variables (in other words, parameters). A typical Angular component has two major parts of logic, a HTML template and a Typescript class. The capability to utilize this kind of function-like HTML segment is essential for a good shared component. It is because a shared component with only a fixed HTML template is very difficult to fit all the needs among all different use cases. Trying to satisfy all potential use cases with a single and fixed HTML template will usually end up with a large template with lots of conditional statements (like *ngIf), which is painful to read and maintain.

Here I would like to explain with an example, about how we can utilize TemplateRef to define function-like HTML segments for communication between templates, which is a good solution to deal with the large template problem.

Image from Pinterest

Getting started

Assume that there is a shared component DataListComponent, which takes an array of data and displays them in the view:

export interface DataTableRow {
dataType: string;
value: any;
}
@Component({
selector: 'data-list',
template: `
<div *ngFor="let row of data" [ngSwitch]="row.dataType">…

--

--

Liu Ting Chun
Liu Ting Chun

Written by Liu Ting Chun

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

Responses (3)