Angular built-in指令分为attribute指令和structural指令两种。
Attribute指令
最常用的attribute指令有NgClass, NgStyle和NgModel三种。
NgClass
动态添加或者删除html标签的css类。
例子:
<!-- toggle the "special" class on/off with a property --> <div [ngClass]="isSpecial ? 'special' : ''">This div is special</div>
isSpecial为true时,div标签打上special的css类。
一个更复杂一些的例子:
<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special.</div>
div的class绑定到了Component的property,名为currentClasses.
在Component的实现代码里,currentclasses的赋值逻辑:
currentClasses: {}; /* . . . */ setCurrentClasses() { // CSS classes: added/removed per current state of component properties this.currentClasses = { saveable: this.canSave, modified: !this.isUnchanged, special: this.isSpecial }; }
NgModel
例子:
<label for="example-ngModel">[(ngModel)]:</label> <input [(ngModel)]="currentItem.name" id="example-ngModel">
上面实际上是一个双向绑定的语法糖,等价于:
<label for="without">without NgModel:</label> <input [value]="currentItem.name" (input)="currentItem.name=$event.target.value" id="without">
Structural指令
ngIf
例子:
<div *ngIf="hero" class="name">{{hero.name}}</div>
实际是个语法糖,等价于:
<ng-template [ngIf]="hero"> <div class="name">{{hero.name}}</div> </ng-template>
ngFor
例子:
<app-item-detail *ngFor="let item of items" [item]="item"></app-item-detail>
let item of items的含义:Take each item in the items array, store it in the local item looping variable, and make it available to the templated HTML for each iteration.
ngFor指令有一个内置属性index:
<div *ngFor="let item of items; let i=index">{{i + 1}} - {{item.name}}</div>
上面的例子,将index属性赋给template变量i.