1
votes

Hello and thanks in advance for your help.

I have an ngFor loop in my angular app within which I am using ngIf to determine which rows to show based on a certain condition. Because I cannot put ngFor and ngIf on the same element, my index goes out of order.

I need the correct index (or odd and even) because I want to highlight rows in an alternating manner.

Any suggestions would be very helpful!

****Edit: Adding code below as example. This is what I'm trying to do. In this example, the row for 'a' will be blue and for 'b' and 'd' will be red. 'c' will be hidden, so the order of colors will be blue, red, red instead of blue, red, blue as I would want. My loop doesn't know that 'c' is not shown and so does not know that 'd' is an even row.

My condition for ngIf is separate from the odd/even condition which is only used for highlighting.

<ng-container *ngFor="let letter of ['a','b','c','d']; let odd = odd ; let even = even">
 <ng-container *ngIf="letter != 'c">
  <div ngClass="{{odd ? 'class-red' : 'class-blue'}}><p>{{a}}</p></div>
 </ng-container>
</ng-container>
2
Please show code, what you have tried and where you are having issue.AT82
you dont't need ngIf, use ngClass for highliting, see stackoverflow.com/questions/36375686/…Turo
@Alex added code aboveaks94
@Turo I don't want the ngif for highlighting, it is only for determining what rows to show. The ngclass as you point out will be used for highlighting but it gets the indices wrong as rows are hiddenaks94

2 Answers

1
votes

For your problem

I would suggest to have your filtered array in component and then do the logic related to odd/even in template. So here you can do it like:

component.ts

private _items: any[];
get Items() {
  return this._items.filter(item => <your condition>);
}

It's just a direction you can optimize this code according to your requirements.

HTML

<ng-container *ngFor="let item of Items; let i = index">
    <div [ngClass]="{'even': i%2 == 0}">{{item.name}}</div>
</ng-container>

PREVIOUS SOLUTIONS

You can use ng-container for loop and then hide/show the div on the basis of condition

<ng-container *ngFor="let item of Items">
    <div *ngIf="item.isValid">Hello {{item.status}}</div>
</ng-container>

If you want to apply CSS you can do following:

<ng-container *ngFor="let item of Items; let i = index">
    <div [ngClass]="{'even': i%2 == 0}">Hello {{item.status}}</div>
</ng-container>
0
votes

Hacky way to do is like this ( Not preferred one but working ) :

Component Side :

isodd = false;

public get changeOdd(){
    this.isodd = !this.isodd;
    return true;
}

Template Side :

<ng-container *ngFor="let letter of ['a','b','c','d']">
 <ng-container *ngIf="letter != 'c' && changeOdd">
  <div ngClass="{{isodd ? 'class-red' : 'class-blue'}}">
    <p>{{letter}} {{ isodd }}</p>
  </div>
 </ng-container>
</ng-container>

WORKING DEMO