前言
指令也是NG的核心部分之一,它可以用來對模板內(nèi)容進行邏輯控制。結(jié)合數(shù)據(jù)綁定使用,基本就告別了手動操作DOM的時代,轉(zhuǎn)而進入了美好的數(shù)據(jù)驅(qū)動的前端高效開發(fā)時代。
分類
- 屬性形指令
可以監(jiān)聽或修改其它 HTML 元素、特性 (attribute)、屬性 (property)、組件的行為。例如ngClass和ngStyle指令。
- 結(jié)構(gòu)性指令
負(fù)責(zé)塑造HTML 結(jié)構(gòu)。一般通過添加、刪除或者操作 HTML 元素及其子元素來實現(xiàn)。例如ngIf和ngFor指令。
- 組件
帶有模板的指令,用于組合程序邏輯和 HTML 模板,渲染出應(yīng)用的視圖。
應(yīng)用
ngClass和ngStyle指令之前我們介紹了,讓我們看看其他指令如何使用吧~
- 微模板指令
通過在指令前面加星號,是一種語法糖。NG會解開這個語法糖,變成一個<ng-template>,里面包裹著宿主元素及其子元素。
- *ngIf="表達式"
表達式為真的時候展現(xiàn)內(nèi)容,這是個微模板指令。
*ngIf="getProductCount()" else="表達式2"(NG4+)
- [ngSwitch]="表達式" *ngSwitchCase="表達式2" *ngSwitchDefault
根據(jù)表達式和表達式2的匹配多選一展示內(nèi)容,這是個微模板指令。使用字面量要用單引號。
<div [ngSwitch]="getProductCount()">
<span *ngSwitchCase="2">There are two products</span>
<span *ngSwitchCase="5">There are five products</span>
<span *ngSwitchDefault>This is the default</span>
</div>
- *ngFor="let item of 表達式"
1.迭代表達式返回的結(jié)果展現(xiàn)內(nèi)容,這是個微模板指令。
2.它還自帶一些模板變量,比如index、odd、even、first、last。
3.應(yīng)對數(shù)據(jù)變更引起的刷新性能問題可以使用trackBy追蹤它。
<tr *ngFor="let item of getProducts()">
<td>{{item.name}}</td>
<td>{{item.category}}</td>
<td>{{item.price}}</td>
</tr>
- [ngTemplateOutlet]="myTempl"
重復(fù)一塊內(nèi)容
<template #titleTemplate>
<h4 class="p-a-1 bg-success">Repeated Content</h4>
</template>
<template [ngTemplateOutlet]="titleTemplate"></template>
- <ng-container>
不影響DOM的容器,也就是說實際渲染時這塊會被丟棄,常常在里面使用結(jié)構(gòu)性指令
自定義指令
通常是利用NG的core庫里的Directive, ElementRef, HostListener,Input等符號實現(xiàn)
- 創(chuàng)建屬性指令
步驟:
1.使用Directive聲明一個指令
2.用ElementRef間接操作DOM
3.用HostListener監(jiān)聽DOM事件
4.使用Input自定義屬性
- 創(chuàng)建結(jié)構(gòu)指令
1.使用Directive聲明一個指令
2.使用ngOnChanges鉤子和SimpleChange檢測屬性變更并更新DOM結(jié)構(gòu)
3.使用TemplateRef和ViewContainerRef管理DOM元素
4.使用$implicit隱式變量提供額外的上下文數(shù)據(jù),實現(xiàn)模板輸入變量
5.和迭代有關(guān)的還要引入IterableDiffer, IterableDiffers,ChangeDetectorRef, CollectionChangeRecord, ViewRef
- 創(chuàng)建組件
1.使用Component聲明一個組件
2.使用ViewChildren裝飾器獲取模板中的元素
3.組件間都是互相隔離的,默認(rèn)影子DOM模式
4.組件充當(dāng)了“控制器 (controller) ”和“視圖模型 (view model) ”的角色
總結(jié)
屬性形指令免去了我們對DOM的style或者classList進行操作、結(jié)構(gòu)指令免去了在js里createElement、appendElement等創(chuàng)建刪除DOM節(jié)點等操作,組件