写一个名叫 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; } }