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微服务练兵》系列索引:https://blog.csdn.net/donjan/article/details/103005084

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值