在 angular 7 中使用 ng-content 动态隐藏子项

Dynamically hiding children using ng-content in angular 7

我的项目中有一个场景,必须根据为特定登录用户提供的角色权限隐藏内容。

所以我们制作了一个名为 <app-authorise> 的全局组件,它将根据用户拥有的权限启用子组件。

Component.ts

import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
import { GlobalService } from '../../../core/global/global.service';

@Component({
  selector: 'app-authorise',
  templateUrl: './app-authorise.component.html',
  styleUrls: ['./app-authorise.component.scss'],
  changeDetection: ChangeDetectionStrategy.Default
})
export class AuthoriseComponent {
  @Input() public module: string;
  @Input() public permission: string;
  @Input() public field: string;
  @Input() public role: string;

  public currentUser: any = {};
  public currentUserRoles = [];
  constructor(private globalService: GlobalService) {
    this.globalService.subscribeToUserSource((updatedUser: any) => {
      this.currentUser = updatedUser;
      this.currentUserRoles = updatedUser.rolePermissions;
    });
  }

  get enable() {
    const {
      currentUser,
      currentUserRoles,
      module,
      permission,
      role
    } = this;
    if (currentUser && currentUserRoles) {
      return role ? this.hasRole(currentUserRoles, role) :
      this.globalService.hasPermissionForModule({
        currentUserRoles,
        module,
        permission,
      });
    }
    return false;
  }

  public hasRole(currentUserRoles: any, role: string) {
    return Boolean(currentUserRoles[role]);
  }
}

Component.html

<ng-container>
  <ng-content *ngIf="enable"></ng-content>
</ng-container>

用例

<app-authorise [module]="properties.modules.project" [permission]="properties.permissions.CREATE">
  <app-psm-list></app-psm-list>
</app-authorise>

我们面临的实际问题是子组件的 onInit() 方法被调用,即使在父组件内部启用了子组件。

任何想法,对此的建议都将非常有帮助。

您可以在将 <app-psm-list> 组件投影到 <app-authorise> 之前检查条件,以便在条件失败时不会调用 app-psm-list 组件 ngOnInit()

为此,您需要一些参考,例如 #authoriseapp-authorise 组件

<app-authorise #authorise [module]="properties.modules.project" [permission]="properties.permissions.CREATE">
  <ng-conatiner *ngIf="authorise.enable">
      <app-psm-list></app-psm-list>
  </ng-conatiner>
</app-authorise>

并且 app-authorise 中不需要条件

应用授权

<ng-container>
  <ng-content></ng-content>
</ng-container>

DEMO

发现这个 custom-permission-directive 真的很有帮助。 可以使用指令代替组件。