Skip to content
Advertisement

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

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).

Advertisement

Answer

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.. 🙂

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement