Angular 自定义结构型指令 structural directive 的使用

Angular的结构型指令的职责是 HTML 布局。 它们塑造或重塑 DOM 的结构,比如添加、移除或维护这些元素。说白了就是对网页的结构进行控制,NgIf,NgFor都是结构型指令。

创建src/app/helpers/directive.ts写一个结构指令appCan

@Directive({ selector: '[appCan]' })
export class CanDirective {

    constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef
    ) { }

    @Input() set appCan(param) { // 接收一个数组的参数,第一个是用户拥有的权限,第二个为需要判断的权限
        const perms = param[0];
        const path = param[1];
        if (perms && perms.indexOf(path) > -1) {
            this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainer.clear();
        }
    }
}

src/app/app-routing.module.ts导入

import { CanDirective} from './helpers/directive';

并添加到declarations

  declarations: [
    ...
    CanDirective,
    ...
  ]

就可以在模板里使用了src/app/views/user/list.component.html,当用户没有/user-center/users/put这个权限的时候,按钮不会展示出来

<button *appCan="[app.permsArr,'/user-center/users/put']" nz-button nzType="primary" (click)='edit(m)'><i nz-icon
                        nzType="edit" nzTheme="outline"></i>编辑</button>

博客:《PHP 微服务练兵》系列教程

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!