How to get 1st true value for *ngIf inside *ngFor

Viewed 472

I have an array of items that need to be displayed based on roles. I need the first value which will fulfil the ngIf condition.

I am adding my code below:

My Array(kind of how it will originally look):

parentTabList = [ 
        {
            name: 'abc',
            label: 'abc',
            icon : 'question_answer',
            role : ['vend_perm','vend_temp','vend_subs']
        },
        {
            name: 'xyz',
            label: 'xyz',
            icon : 'question_answer',
            role : ['vend_perm','vend_subs']
        }
    ]

My Html: -

<ng-container *ngFor="let form of parentTabList let i = index">
    <li *ngIf="form.role.includes(userRole)">
        <a (click)="methodName(form)">
            {{form.label}}
        </a>
    </li>
</ng-container>

UserRole is a string value that I get when a user logs-in.

I need to add a ngClass to the anchor tag if it is the first anchor to be displayed. (I am a noob at StackOverflow, please let me know if any more explanation is required).

3 Answers

You can write like this. In this code, f represents the first position of your array.

<ng-container *ngFor="let form of parentTabList; let i = index; let f = first">
    <li *ngIf="f">
        <a (click)="methodName(f)">
            `{{f.label}}`
        </a>
    </li>
</ng-container>

If you want other position of your array, you can write like you mentioned above.

You can identify first element of the array with index.

But as per my understanding you need filter this array with roles and then apply ngClass to first element from filtered list.

So add method to return filtered array with respect to roles

In Template:

 filterParentTabList(parentList: any) {
     return parentList.filter(form => form.role.includes(this.userRole));
 }

In View:

<ng-container *ngFor="let form of filterParentTabList(parentTabList); let i = index">
    <li>
        <a [ngClass]="{ 'addYourClaaName': i === 0 }" (click)="methodName(form)">
            {{form.label}}
        </a>
    </li>
</ng-container>

Happy Coding.. :)

You can define a getter that will get you the index. This can then be used in the html

  get firstIndex() {
    return this.parentTabList.indexOf(this.parentTabList.find(({role}) => 
      role.includes(this.userRole)))
  }

Now in your html

<ng-container *ngFor="let form of parentTabList let i = index">
    <li *ngIf="form.role.includes(userRole)">
        <a [ngClass]="{redText: firstIndex === i}" (click)="methodName(form)">
            {{form.label}}
        </a>
    </li>
</ng-container>

See Stackblitz Demo Here

Related