Florian
Florian

Reputation: 39

Angular looping problem with ngIf and ngFor on arrays

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

Upvotes: 0

Views: 141

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

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> 

Upvotes: 3

Related Questions