<div *ngIf="false"></div> <!-- never displayed --> <div *ngIf="a > b"></div> <!-- displayed if a is more than b --> <div *ngIf="str == 'yes'"></div> <!-- displayed if str holds the string "yes" --> <div *ngIf="myFunc()"></div> <!-- displayed if myFunc returns a true value -->
有時候須要根據不一樣的條件,渲染不一樣的元素,此時咱們可使用多個ngIf來實現。css
<div class="container"> <div *ngIf="myVar == 'A'">Var is A</div> <div *ngIf="myVar == 'B'">Var is B</div> <div *ngIf="myVar != 'A' && myVar != 'B'">Var is something else</div> </div>
若是myVar的可選值多了一個'C',就得相應增長判斷邏輯:express
<div class="container"> <div *ngIf="myVar == 'A'">Var is A</div> <div *ngIf="myVar == 'B'">Var is B</div> <div *ngIf="myVar == 'C'">Var is C</div> <div *ngIf="myVar != 'A' && myVar != 'B' && myVar != 'C'"> Var is something else </div> </div>
能夠發現 Var is something else 的判斷邏輯,會隨着 myVar 可選值的新增,變得愈來愈複雜。遇到這種情景,咱們可使用 ngSwitch 指令。segmentfault
<div class="container" [ngSwitch]="myVar"> <div *ngSwitchCase="'A'">Var is A</div> <div *ngSwitchCase="'B'">Var is B</div> <div *ngSwitchCase="'C'">Var is C</div> <div *ngSwitchDefault>Var is something else</div> </div>
NgStyle讓咱們能夠方便的經過Angular表達式,設置DOM元素的css屬性。api
<div [style.background-color="'yellow'"]> Use fixed yellow background </div>
<!-- 支持單位: px | em | %--> <div> <span [ngStyle]="{color: 'red'}" [style.font-size.px]="fontSize"> red text </span> </div>
NgStyle支持經過鍵值對的形式設置DOM元素的樣式:數組
<div [ngStyle]="{color: 'white', 'background-color': 'blue'}"> Uses fixed white text on blue background </div>
注意到 background-color 須要使用單引號,而 color 不須要。這其中的緣由是,ng-style 要求的參數是一個 Javascript 對象,color 是一個有效的 key,而 background-color 不是一個有效的 key ,因此須要添加 ''。app
@Directive({selector: '[ngStyle]'}) export class NgStyle implements DoCheck { private _ngStyle: {[key: string]: string}; private _differ: KeyValueDiffer<string, string|number>; constructor( private _differs: KeyValueDiffers, private _ngEl: ElementRef, private _renderer: Renderer) {} @Input() set ngStyle(v: {[key: string]: string}) { // <div [ngStyle]="{color: 'white', 'background-color': 'blue'}"> this._ngStyle = v; if (!this._differ && v) { this._differ = this._differs.find(v).create(); } } // 設置元素的樣式 private _setStyle(nameAndUnit: string, value: string|number): void { const [name, unit] = nameAndUnit.split('.'); // 截取樣式名和單位 value = value != null && unit ? `${value}${unit}` : value; this._renderer.setElementStyle(this._ngEl.nativeElement, name, value as string); } }
NgClass接收一個對象字面量,對象的key是CSS class的名稱,value的值是truthy/falsy的值,表示是否應用該樣式。dom
.bordered { border: 1px dashed black; background-color: #eee; }
<!-- Use boolean value --> <div [ngClass]="{bordered: false}">This is never bordered</div> <div [ngClass]="{bordered: true}">This is always bordered</div> <!-- Use component instance property --> <div [ngClass]="{bordered: isBordered}"> Using object literal. Border {{ isBordered ? "ON" : "OFF" }} </div> <!-- Class names contains dashes --> <div[ngClass]="{'bordered-box': false}"> Class names contains dashes must use single quote </div> <!-- Use a list of class names --> <div class="base" [ngClass]="['blue', 'round']"> This will always have a blue background and round corners </div>
NgFor指令用來根據集合(數組),建立DOM元素,相似於ng1中的ng-repeat指令angular4
<div class="ui list" *ngFor="let c of cities; let num = index"> <div class="item">{{ num+1 }} - {{ c }}</div> </div>
使用trackBy提升列表的性能async
@Component({ selector: 'my-app', template: ` <ul> <li *ngFor="let item of collection;trackBy: trackByFn">{{item.id}}</li> </ul> <button (click)="getItems()">Refresh items</button> `, }) export class App { constructor() { this.collection = [{id: 1}, {id: 2}, {id: 3}]; } getItems() { this.collection = this.getItemsFromServer(); } getItemsFromServer() { return [{id: 1}, {id: 2}, {id: 3}, {id: 4}]; } trackByFn(index, item) { return index; // or item.id } }
NgNonbindable指令用於告訴Angular編譯器,無需編譯頁面中某個特定的HTML代碼片斷性能
<div class='ngNonBindableDemo'> <span class="bordered">{{ content }}</span> <span class="pre" ngNonBindable> ← This is what {{ content }} rendered </span> </div>
If...Else Template Conditions
語法
<element *ngIf="[condition expression]; else [else template]"></element>
使用實例
<ng-template #hidden> <p>You are not allowed to see our secret</p> </ng-template> <p *ngIf="shown; else hidden"> Our secret is being happy </p>
<
template> --><
ng-template>
使用實例
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/delay'; @Component({ selector: 'exe-app', template: ` <ng-template #fetching> <p>Fetching...</p> </ng-template> <p *ngIf="auth | async; else fetching; let user"> {{user.username }} </p> `, }) export class AppComponent implements OnInit { auth: Observable<{}>; ngOnInit() { this.auth = Observable .of({ username: 'semlinker', password: 'segmentfault' }) .delay(new Date(Date.now() + 2000)); } }
<div [hidden]="!showGreeting"> Hello, there! </div>
上面的代碼在一般狀況下,都能正常工做。但當在對應的DOM元素位置上設置display:flex屬性時,儘管[hidden]對應的表達式true,但元素卻能正常顯示。對於這種特殊狀況,則推薦使用*ngIf。
@Component({ selector: 'my-comp', template: ` <input type="text" /> <div> Some other content </div> ` }) export class MyComp { constructor(el: ElementRef) { el.nativeElement.querySelector('input').focus(); } }
以上的代碼直接經過 querySelector() 獲取頁面中的元素,一般不推薦使用這種方式。更好的方案是使用 @ViewChild 和模板變量,具體示例以下:
@Component({ selector: 'my-comp', template: ` <input #myInput type="text" /> <div> Some other content </div> ` }) export class MyComp implements AfterViewInit { @ViewChild('myInput') input: ElementRef; constructor(private renderer: Renderer) {} ngAfterViewInit() { this.renderer.invokeElementMethod( this.input.nativeElement, 'focus'); } }
另外值得注意的是,@ViewChild() 屬性裝飾器,還支持設置返回對象的類型,具體使用方式以下:
@ViewChild('myInput') myInput1: ElementRef; @ViewChild('myInput', {read: ViewContainerRef}) myInput2: ViewContainerRef;
若未設置 read 屬性,則默認返回的是 ElementRef 對象實例。