Angular 2.x學習教程之結構指令詳解
結構指令是什么?
結構指令通過添加和刪除 DOM 元素來更改 DOM 布局。Angular 中兩個常見的結構指令是 *ngIf 和 *ngFor 。
了解 * 號語法
* 號是語法糖,用于避免使用復雜的語法。我們以 *ngIf 指令為例:

(圖片來源:https://netbasal.com/)
- Angular 把 host (宿主元素) 包裝在 template 標簽里面
- Angular 將 ngIf 轉換為屬性綁定 - [ngIf]
創(chuàng)建結構指令
首先,讓我們了解如何創(chuàng)建一個結構指令。 接下來我們將要實現(xiàn)一個簡單的 ngIf 指令。
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({ selector: '[myNgIf]'})
export class MyNgIfDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) { }
@Input() set myNgIf(condition: boolean) {
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
我們可以按照以下方式使用我們的指令:
<div *myNgIf=”condition”></div>
下面我們來解釋一下上面的代碼。
TemplateRef
如名字所示,TemplateRef 用于表示模板的引用。

(圖片來源:https://netbasal.com/)
ViewContainerRef
正如上面介紹的,模板中包含了 DOM 元素,但如果要顯示模板中定義的元素,我們就需要定義一個插入模板中元素的地方。在 Angular 中,這個地方被稱作容器,而 ViewContainerRef 用于表示容器的引用。那什么元素會作為容器呢?
Angular 將使用 comment 元素替換 template 元素,作為視圖容器。
我們來看一個具體的示例:
@Component({
selector: 'my-app',
template: `
<div>
<h2 *myNgIf="condition">Hello {{name}}</h2>
<button (click)="condition = !condition">Click</button>
</div>
`,
})
export class App {
name: string;
condition: boolean = false;
constructor() {
this.name = 'Angular2'
}
}
以上代碼成功運行后,瀏覽器的顯示內容如下:

(圖片來源:https://netbasal.com/)
ViewContainerRef 對象提供了 createEmbeddedView() 方法,該方法接收 TemplateRef 對象作為參數(shù),并將模板中的內容作為容器 (comment 元素) 的兄弟元素,插入到頁面中。
現(xiàn)在,你已經(jīng)了解如何創(chuàng)建結構指令,接下來讓我們看看兩個具體的實例。
基于用戶角色顯示不同的內容
指令定義
@Directive({selector: '[ifRole]'})
export class IfRoleDirective {
user$ : Subscription;
@Input("ifRole") roleName : string;
constructor(
private templateRef : TemplateRef<any>,
private viewContainer : ViewContainerRef,
private authService : AuthService ) {}
ngOnInit() {
this.user$ = this.authService.user
.do(() => this.viewContainer.clear())
.filter(user => user.role === this.roleName)
.subscribe(() => {
this.viewContainer.createEmbeddedView(this.templateRef);
});
}
ngOnDestroy() {
this.user$.unsubscribe();
}
}
指令應用
<div *ifRole="'admin'"> Only for Admin </div> <div *ifRole="'client'"> Only for Client </div> <div *ifRole="'editor'"> Only for Editor </div>
創(chuàng)建 Range 指令
指令定義
import { Directive, Input, ViewContainerRef, TemplateRef } from '@angular/core';
@Directive({
selector: '[range]'
})
export class RangeDirective {
_range: number[];
@Input()
set range(value: number) {
this.vcr.clear();
this._range = this.generateRange(value[0], value[1]);
this._range.forEach(num => {
this.vcr.createEmbeddedView(this.tpl, {
$implicit: num
});
});
}
constructor(
private vcr: ViewContainerRef,
private tpl: TemplateRef<any>) { }
private generateRange(from: number, to: number): number[] {
var numbers: number[] = [];
for (let i = from; i <= to; i++) {
numbers.push(i);
}
return numbers;
}
}
以上示例中,我們在調用 createEmbeddedView() 方法時,設置了第二個參數(shù) {$implicit: num} 。Angular 為我們提供了 let 模板語法,允許在生成上下文時定義和傳遞上下文。
這將允許我們引用 *range="[20,30]; let num" 模板中聲明的變量。我們使用 $implicit 名稱,因為我們不知道用戶在使用這個指令時,會使用什么名字。

(圖片來源:https://netbasal.com/)
指令應用
<h1>Your age:</h1>
<select>
<ng-container *range="[18, 80]; let num">
<option [ngValue]="num">{{num}}</option>
</ng-container>
</select>
<h1>Year:</h1>
<select>
<ng-container *range="[1998, 2016]; let num">
<option [ngValue]="num">{{num}}</option>
</ng-container>
</select>
以上代碼成功運行后,瀏覽器的顯示內容如下:

(圖片來源:https://netbasal.com/)
總結
以上就是這篇文章的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
angular 數(shù)據(jù)綁定之[]和{{}}的區(qū)別
這篇文章主要介紹了angular 數(shù)據(jù)綁定之[]和{{}}的區(qū)別,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-09-09
使用Angular CLI快速創(chuàng)建Angular項目的一些基本概念和寫法小結
這篇文章主要介紹了使用Angular CLI快速創(chuàng)建Angular項目的一些基本概念和寫法小結,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04
Angular6 Filter實現(xiàn)頁面搜索的示例代碼
這篇文章主要介紹了Angular6 Filter實現(xiàn)頁面搜索的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12

