寫一個名叫 kylinAcl
的結構型指令,用做控制頁面上的按鈕根據後端返回的權限是否刪除和添加。typescript
<button *kylinAcl="'button'">應該顯示</button>
建立指令很像建立組件。後端
這裏是列表文本導入 Directive 裝飾器(而再也不是 Component)。this
導入符號 Input、TemplateRef 和 ViewContainerRef,你在任何結構型指令中都會須要它們。code
給指令類添加裝飾器。ip
設置 CSS 屬性選擇器 ,以便在模板中標識出這個指令該應用於哪一個元素。string
這裏是起點:模板
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[kylinAcl]' })
聲明變量class
buttonList: Array<string>; private hasView = false; private allow = false;
實現代碼:angular
@Input() set kylinAcl(buttonName: string) { this.buttonList.forEach((allowName) => { // 從拿到的按鈕權限裏面查找是否有此按鈕名稱 if (allowName === buttonName) { this.allow = true; } }); if (this.allow) { // 應該顯示 this.viewContainerRef.createEmbeddedView(this.templateRef); this.hasView = true; } else if (!this.allow) { // 應該從DOM移除 這裏直接使用else沒問題,使用else if 徹底是做者喜愛問題 this.viewContainerRef.clear(); this.hasView = false; } }