NgIf
<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 -->
NgSwitch
有時(shí)候需要根據(jù)不同的條件崔步,渲染不同的元素村视,此時(shí)我們可以使用多個(gè) ngIf
來(lái)實(shí)現(xiàn)坚弱。
<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
的可選值多了一個(gè) 'C'
斧拍,就得相應(yīng)增加判斷邏輯:
<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>
可以發(fā)現(xiàn) Var is something else
的判斷邏輯雀扶,會(huì)隨著 myVar
可選值的新增,變得越來(lái)越復(fù)雜肆汹。遇到這種情景愚墓,我們可以使用 ngSwitch
指令。
<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
NgStyle 讓我們可以方便得通過(guò) Angular 表達(dá)式昂勉,設(shè)置 DOM 元素的 CSS 屬性浪册。
- 設(shè)置元素的背景顏色
<div [style.background-color="'yellow'"]>
Use fixed yellow background
</div>
- 設(shè)置元素的字體大小
<!-- 支持單位: px | em | %-->
<div>
<span [ngStyle]="{color: 'red'}" [style.font-size.px]="fontSize">
red text
</span>
</div>
NgStyle 支持通過(guò)鍵值對(duì)的形式設(shè)置 DOM 元素的樣式:
<div [ngStyle]="{color: 'white', 'background-color': 'blue'}">
Uses fixed white text on blue background
</div>
注意到 background-color
需要使用單引號(hào),而 color
不需要岗照。這其中的原因是村象,ng-style
要求的參數(shù)是一個(gè) Javascript
對(duì)象笆环,color
是一個(gè)有效的 key
,而 background-color
不是一個(gè)有效的 key
厚者,所以需要添加 ''
咧织。
NgClass
NgClass 接收一個(gè)對(duì)象字面量,對(duì)象的 key
是 CSS class 的名稱(chēng)籍救,value
的值是 truthy/falsy
的值习绢,表示是否應(yīng)用該樣式。
- CSS Class
.bordered {
border: 1px dashed black; background-color: #eee;
}
- HTML
<!-- 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
NgFor 指令用來(lái)根據(jù)集合(數(shù)組) 蝙昙,創(chuàng)建 DOM
元素闪萄,類(lèi)似于 ng1
中 ng-repeat
指令
<div class="ui list" *ngFor="let c of cities; let num = index">
<div class="item">{{ num+1 }} - {{ c }}</div>
</div>
使用 trackBy
提高列表的性能
@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
ngNonBindable 指令用于告訴 Angular 編譯器,無(wú)需編譯頁(yè)面中某個(gè)特定的HTML代碼片段奇颠。
<div class='ngNonBindableDemo'>
<span class="bordered">{{ content }}</span>
<span class="pre" ngNonBindable>
← This is what {{ content }} rendered
</span>
</div>
Angular 4.x 新特性
If...Else Template Conditions
語(yǔ)法
<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));
}
}
我有話(huà)說(shuō)
使用 [hidden]
屬性控制元素可見(jiàn)性存在的問(wèn)題
<div [hidden]="!showGreeting">
Hello, there!
</div>
上面的代碼在通常情況下败去,都能正常工作。但當(dāng)在對(duì)應(yīng)的 DOM 元素上設(shè)置 display: flex
屬性時(shí)烈拒,盡管[hidden]
對(duì)應(yīng)的表達(dá)式為 true
圆裕,但元素卻能正常顯示。對(duì)于這種特殊情況荆几,則推薦使用 *ngIf
吓妆。
直接使用 DOM
API 獲取頁(yè)面上的元素存在的問(wèn)題
@Component({
selector: 'my-comp',
template: `
<input type="text" />
<div> Some other content </div>
`
})
export class MyComp {
constructor(el: ElementRef) {
el.nativeElement.querySelector('input').focus();
}
}
以上的代碼直接通過(guò) querySelector()
獲取頁(yè)面中的元素,通常不推薦使用這種方式吨铸。更好的方案是使用 @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()
屬性裝飾器诞吱,還支持設(shè)置返回對(duì)象的類(lèi)型舟奠,具體使用方式如下:
@ViewChild('myInput') myInput1: ElementRef;
@ViewChild('myInput', {read: ViewContainerRef}) myInput2: ViewContainerRef;
若未設(shè)置 read
屬性,則默認(rèn)返回的是 ElementRef
對(duì)象實(shí)例房维。