Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some Angular directives need to start with *?

Tags:

angular

Why do some directives need to start with *? For instance, in the following code snippet, directive matHeaderCellDef starts with *. Instead, matColumnDef doesn't.

<ng-container matColumnDef="position">
  <th mat-header-cell *matHeaderCellDef> Tag </th>
  <td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>
like image 679
Roger Xi Avatar asked Oct 27 '25 07:10

Roger Xi


2 Answers

The answers are in the Angular docs and source codes.

Without asterisk -> attribute directive https://angular.io/guide/attribute-directives

With asterisk -> structural directive https://angular.io/guide/structural-directives

like image 176
Roger Xi Avatar answered Oct 29 '25 23:10

Roger Xi


The * is a bit of syntactic sugar that makes it easier to read and write directives that modify HTML layout with the help of templates. NgFor, NgIf, and NgSwitch all add and remove element subtrees that are wrapped in tags.

ngFor can only be applied to a <template>. *ngFor is the short form that can be applied to any element and the <template> element is created implicitly behind the scene.

https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

Syntax

<li *ngFor="let item of items; let i = index">...</li>
<li template="ngFor let item of items; let i = index">...</li>
<template ngFor let-item [ngForOf]="items" let-i="index"><li>...</li>

Used for all structural Directive

What is this * for? As you can see there’s no more ng-repeat, it’s ngFor now. why the asterisk? The answer to that is, it’s syntactic sugar. ngFor can only be applied to a <template>. *ngFor is the short form that can be applied to any element and the <template> element is created implicitly behind the scene. The * makes it easier to read and write directives that modify HTML layout with the help of templates. NgFor, NgIf, and NgSwitch all add and remove element subtrees that are wrapped in <template> tags.

The HTML template element <template> is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during run time using JavaScript. Think of a template as a content fragment that is being stored for subsequent use in the document.