ng中利用自定义指令实现权限控制dom显示隐藏

项目中要根据角色权限去判断一些操作按钮是否显示。一个一个处理太麻烦,因此做了一个统一的指令进行处理。

首先项目上增加了一个dom权限配置的地方,在配置里利用dom标识实现和角色权限的绑定,然后前端通过请求后端拿到当前人员是否能看到配置的dom元素。

前端自定义指令代码

import {Directive, ElementRef, Input, OnInit, Renderer2} from '@angular/core';
import {UserService} from "./user/user-service";

@Directive({
selector: '[authIdentify]'
})
export class AuthorityDirective implements OnInit {

constructor(
private el: ElementRef,
private renderer2: Renderer2,
private userInfoService: UserInfoService) {
}

@Input() title: string = '';
@Input() authPlace: boolean; // 是否占位
@Input('authIdentify') authIdentify: string; // 权限标识

// 用例 供应商信息库
ngOnInit() {

if (this.authIdentify) {
this.el.nativeElement.style.display = 'none';
this.userService.getAuthority(this.authIdentify).subscribe(info => {
if (info && info.length > 0) {
this.el.nativeElement.style.display = '';
return;
} else {
if (this.authPlace) {
this.el.nativeElement.style.visibility = 'hidden';
if (this.title) {
const text = this.renderer2.createElement('span');
text.innerHTML = this.title;
text.style.visibility = 'visible';
text.style.color = '#ccc';
this.renderer2.appendChild(this.el.nativeElement, text);
}
} else {
this.el.nativeElement.style.display = 'none';
}
}
})
}
}
}

在共享module里面注入这个指令
使用:
<button nz-button [nzType]="'primary'" [authIdentify]="'user_add'">人员新增</button>

猜你喜欢

转载自www.cnblogs.com/canghaishui/p/12435238.html
今日推荐