0

in my ng app I'm working with roles. All roles are stored in an array. How can I check if a role exists in my html template without doing something like this:

  <div class="customer-entry" *ngFor="role of userRoles">
    <div *ngIf="role == 'Admin' || role == 'Superuser'">
      <span class="badge badge-warning">allowed</span>
    </div>
  </div>

In my opinion there must be a solution to do this without a ngFor.

0

2 Answers 2

1

I would define a structural directive for this:

import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';

@Directive({ 
     selector: '[hasRole]' 
})
export class HasRoleDirective {

    constructor( private templateRef: TemplateRef<any>,
                 private viewContainer: ViewContainerRef,
                 private userService: UserService) { }
    @Input() set hasRole(role: string) {
       if (this.userService.getRole() === role) {
          this.viewContainer.createEmbeddedView(this.templateRef);
       } else {
          this.viewContainer.clear();
      } 
    }
}

You now can use the directive like this:

<div *hasRole="'Admin'">
  <span class="badge badge-warning">allowed</span>
</div>

Benefit would be that you can use it anywhere in your project without duplicating code.

Sign up to request clarification or add additional context in comments.

Comments

0

One way would be using a pipe, this is also faster (if it's pure) than using a service

@Pipe({ name: 'hasPermission' })
export class HasPermission implements PipeTransform {

  transform(permissions: string[], required: string[]): boolean {
    return permissions.some((current) => required.some((req) => current === req));
  }
}

Use it as

 <div class="customer-entry" *ngIf="userRoles | hasPermission: ['Admin', 'Superuser']">
    <div>
      <span class="badge badge-warning">allowed</span>
    </div>
  </div>

Or

  <div class="customer-entry" *ngFor="lot role of userRoles">
    <div *ngIf="[role] | hasPermission: ['Admin', 'Superuser']">
      <span class="badge badge-warning">allowed</span>
    </div>
  </div>

Haven't tested it, this is just a prototype

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.