【问题标题】:Dynamically hiding children using ng-content in angular 7在 Angular 7 中使用 ng-content 动态隐藏子项
【发布时间】:2019-02-17 07:15:27
【问题描述】:

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

所以我们创建了一个名为<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() 方法被调用,即使子组件在父组件中启用。

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

【问题讨论】:

  • 尝试创建动态组件而不是投影组件

标签: javascript angular components parent-child angular7


【解决方案1】:

您可以在将&lt;app-psm-list&gt;组件投影到&lt;app-authorise&gt;之前检查条件,这样如果条件失败,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

【讨论】:

  • 就像一个魅力。谢谢阿米特。现在必须更改代码:)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-18
    • 2016-01-11
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 2019-09-29
    • 2017-06-30
    • 2017-03-03
    相关资源
    最近更新 更多