angular 2 why asterisk (*)
In angular 2 document, * and template, we know that the *ngIf, *ngSwitch, *ngFor can be expanded to template tag. My question is:
I think the ngIf
or ngFor
without *
can also be translated and expanded to template tag by angular engine. So why bother designing a strange symbol asterisk( *
) in angular 2?
<hero-detail *ngIf="currentHero" [hero]="currentHero"></hero-detail>
<template [ngIf]="currentHero">
<hero-detail [hero]="currentHero"></hero-detail>
</template>
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>
Angular2 offers a special kind of directives - Structural directives
Structural directives are base on the <template>
tag.
The *
before the attribute selector indicates that a structural directive should be applied instead of a normal attribute directive or property binding. Angular2 internally expands the syntax to an explicit <template>
tag.
Since final there is also the <ng-container>
element that can be used similarly to the <template>
tag but supports the more common short-hand syntax. This is for example required when two structural directives should be applied to a single element, which is not supportd.
<ng-container *ngIf="boolValue">
<div *ngFor="let x of y"></div>
</ng-container>
Angular treats template elements in a special way. The *
syntax is a shortcut that lets you void writing the whole <template>
element. Let me show you how it works.
using this
*ngFor="let t of todos; let i=index"
de-sugars it into
template="ngFor: let t of todos; let i=index"
which de-sugars into
<template ngFor [ngForOf]="todos" .... ></template>
also angular's Structural directives like ngFor, ngIf etc prefixed by *
just to differentiate from this custom directives and components
see more here
https://vsavkin.com/angular-2-template-syntax-5f2ee9f13c6a#.rcffirs7a
链接地址: http://www.djcxy.com/p/31042.html上一篇: DevExtreme Angular2表单的自定义标签
下一篇: 角2为什么星号(*)