Angular 2 why asterisk (*)

maxisacoder picture maxisacoder · Oct 17, 2016 · Viewed 29.6k times · Source

In angular 2 document, * and template, we know that the *ngIf, *ngSwitch, *ngFor can be expanded to ng-template tag. My question is:

I think the ngIf or ngFor without * can also be translated and expanded to template tag by angular engine.

The following code

<hero-detail *ngIf="currentHero" [hero]="currentHero"></hero-detail>

would be the same as

<ng-template [ngIf]="currentHero">
  <hero-detail [hero]="currentHero"></hero-detail>
</ng-template>

So why bother designing a strange symbol asterisk(*) in angular 2?

Answer

Klaster_1 picture Klaster_1 · Oct 17, 2016

Asterisk syntax is a syntatic sugar for more wordy template syntax which directive expands to under the hood, you are free to use any of these options.

Quote from the docs:

The asterisk is "syntactic sugar". It simplifies ngIf and ngFor for both the writer and the reader. Under the hood, Angular replaces the asterisk version with a more verbose form.

The next two ngIf examples are effectively the same and we may write in either style:

<!-- Examples (A) and (B) are the same -->

<!-- (A) *ngIf paragraph -->
<p *ngIf="condition">
  Our heroes are true!
</p>

<!-- (B) [ngIf] with template -->
<template [ngIf]="condition">
  <p>
    Our heroes are true!
  </p>
</template>