Angular自定义指令实现角色权限控制

一、创建AuthDirective

ng g d auth

 二、修改ngOnChanges方法并添加视图监听方法

purview(roles): boolean {
    const moduleName = this.router.routerState.snapshot.url.split('/')[3];
    const userRoles = this.getSession('userinfo').roles;
    let roleList =
      userRoles.find((item) => item.role === moduleName)?.list || [];
    for (let i = 0; i < roles.length; i++) {
      if (roleList.includes(roles[i])) {
        return true;
      }
    }
    return false;
  }
import {
  Directive,
  Input,
  OnChanges,
  SimpleChanges,
  TemplateRef,
  ViewContainerRef,
} from '@angular/core';
import { AuthService } from 'src/app/@core/services/auth.service';

@Directive({
  selector: '[appAuth]',
})
export class AuthDirective implements OnChanges {
  @Input('appAuth') roles: string[] = [];
  hasView = false;
  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private authService: AuthService
  ) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (this.authService.purview(this.roles)) {
      this.createView();
    } else {
      this.viewContainer.clear();
      this.hasView = false;
    }
  }

  // 创建视图
  private createView(): void {
    this.viewContainer.createEmbeddedView(this.templateRef);
    this.hasView = true;
  }
}

三、模块内引入指令并在组件内使用

1. 对应的Module内引入import { AuthDirective } from './directive/auth.directive';并在declarations和export(外模块需要使用的话)中添加

2.在角色控制的组件内传入角色限制条件(传入的条件为对应的角色所包含的操作权限,我的系统内区分为all/edit/readonly)

<app-module-owner-change
                    *appAuth="['all']"
                    [module]="'auto-test'"
                  ></app-module-owner-change>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular 中,你可以通过自定义指令来扩展 HTML 元素的行为和功能。下面是自定义指令的基本步骤: 1. 创建指令类: - 创建一个新的类,用于定义你的指令。 - 使用 `@Directive` 装饰器来标记该类为一个指令,并传入一个配置对象。 下面是一个示例: ```typescript import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appCustomDirective]' }) export class CustomDirective { constructor(private elementRef: ElementRef) { this.elementRef.nativeElement.style.backgroundColor = 'yellow'; } } ``` 在上面的示例中,我们创建了一个名为 `CustomDirective` 的指令类,并使用 `@Directive` 装饰器来标记它为一个指令。`selector` 属性指定了该指令在模板中的使用方式,这里使用的是属性选择器 `[appCustomDirective]`。 2. 在模板中应用指令: - 在需要应用指令的元素上使用指令的选择器,可以是属性选择器、类选择器或标签选择器。 下面是一个示例: ```html <div appCustomDirective>Custom Directive Example</div> ``` 在上面的示例中,我们使用 `[appCustomDirective]` 属性选择器将自定义指令应用到了 `<div>` 元素上。 3. 使用指令提供的功能: - 在指令类中可以定义各种功能,如修改元素样式、监听事件、操作 DOM 等。 - 在构造函数中可以注入依赖,如 `ElementRef` 用于操作元素。 在上面的示例中,我们在指令类的构造函数中注入了 `ElementRef`,使用它来获取指令所应用的元素,并修改其背景颜色为黄色。 通过以上步骤,你就可以创建和使用自定义指令了。可以根据需求在指令类中实现各种功能,并在模板中应用指令来扩展元素的行为和功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值