Search code examples
angularngforangular-ng-if

Angular2 ngfor index which ignores rows not shown using ngif


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>

Solution

  • 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