Search code examples
htmlangularngforangular-ng-if

Assign a value to a boolean variable in loop * ngFor


I have a ngFor loop in my component window-containerwhere I have several chat window (window-item) that are displayed. I want to set a variable (changeColor) to true for one div on two, and false for the other div on two. I want to be able to use this variable in both components : window-container and window-item.

This is what I did in window-container.html but it does not work :

<window-item
  *ngFor="let thread of windows; let i = index"
    [thread]="thread">
      <div *ngIf="i % 2 == 0"> {{this.threadService.changeColor = false}}</div>
      <div *ngIf="i % 2 != 0"> {{this.threadService.changeColor = true}}
    </div>
</window-item>

I want that the variable changeColor change value for each div for write this in my window-item.html :

<div [ngClass]="{'window-grey' : !this.threadService.changeColor, 'window-blue': this.threadService.changeColor}">
    <div class="panel-container">
      <div class="panel panel-default">
        ...
      </div>
    </div>
</div>

And my window-item.scss :

.panel-heading {
   .top-bar {
      .window-grey {
         background: grey;
      }
      .window-grey {
         background: grey;
      }
   }
}

Solution

  • You can use it like :

    Would suggest you should pass that via odd / even of ngFor

    even: boolean: True when the item has an even index in the iterable.

    odd: boolean: True when the item has an odd index in the iterable.

    <window-item
      *ngFor="let thread of windows; let i = index ; let odd = odd;"
        [thread]="{ thread : thread , changeColor : odd }">
          <!-- <div *ngIf="i % 2 == 0"> {{this.threadService.changeColor = false}} </div>
          <div *ngIf="i % 2 != 0"> {{this.threadService.changeColor = true}} </div> -->
    </window-item>
    
    // window-item.html
    <div [ngClass]="{'window-grey' : !changeColor, 'window-blue': changeColor}">
        <div class="panel-container">
          <div class="panel panel-default">
            ...
          </div>
        </div>
    </div>
    

    WORKING DEMO