javascripthtmlangularngforng-style

ngStyle applying to all elements in ngFor


I am attempting to configure this Angular/Html/JS so that the elements begin to have a blue background when counter >= 5

<p
  *ngFor="let log of clickLog"
  [ngStyle]="{backgroundColor: counter >= 5 ? 'blue' : 'transparent'}">
  {{ log }}
</p>

when the counter is <= 4, all elements have no styling, as intended. The problem is: once the counter hits 5, ALL elements take on the blue background. My intention is that only elements 5+ have the background.

Edit: I am aware that I can use an index value from the ngFor-loop as an alternative solution. I am specifically curious why this approach does not work.


Solution

  • The binding of counter inside [ngStyle] is called property binding which mean Angular will observe and evaluate all [ngStyle] in your <p> tag again and again whenever it dectects changes from counter value.(your misunderstanding is that counter value is evaluated and scoped in each loop)

    That why when counter become higher than 5, all [ngStyle] is evaluated again and have the style backgroundColor:blue. Therefore currently there is no way to archive what you want with only one property counter from your TS file.

    I would suggest using *ngFor 's index which it's value is evaluated and scoped in each loop:

    <p
      *ngFor="let log of clickLog; let indexOfElement = index;"
      [ngStyle]="{'background-color': (indexOfElement >= 4) ? 'blue' : ''}">
      {{ log }}
    </p>