0

I have a rather specific problem concerning *ngIf and *ngFor (I am also open for other solutions, though)

In my application, I get an array of five roles [admin, master, member, user1, user2]. Depending on the roles, I need to provide the anchor tags in the menu, eg. if my role is "admin" I shall get <a>toAdmin</a> etc:

<ng-container *ngFor="let role of roles">
   <ul>
      <li *ngIf="role === 'admin'">
         <a mat-list-item routerLinkActive="list-item-active" routerLink="/admin">
         Admin
         </a>
      </li>
      <li *ngIf="role === 'master'">...</li>
   <ul>
</ng-container> 

This works fine if the array consist only of one role eg. "admin" or "user". However, it can happen that the "roles"-array consist of two or more roles, eg. ['member','user1','user2'] in this case the anchor-tags will appear several times, <a>toUser</a><a>toUser</a>.

<ng-container *ngFor="let role of roles">
   <ul>
      <li *ngIf="role === 'user1' || 'user2'">
         <a mat-list-item routerLinkActive="list-item-active" routerLink="/user">
         User
         </a>
      </li>
      <li *ngIf="role === 'master'">...</li>
   <ul>
</ng-container> 

The result is plausible, anyhow, I only want that one anchor-tag appears.

How would I accomplish that?

Thanks in advance, any help is appreciated.

Florian

1 Answer 1

3

The number of roles a user has shouldn't decide how many links are shown.

I see no need for a loop here at all if you know in advance what links you can potentially render. You can set up your full menu, and then apply a conditional filter.

<ng-container>
   <ul>
      <li *ngIf="user.roles.includes('admin')">
         <a mat-list-item routerLinkActive="list-item-active" routerLink="/admin">
         Admin
         </a>
      </li>
      <li *ngIf="user.roles.includes('master')">...</li>
   <ul>
</ng-container> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.