简体   繁体   中英

Why does this ngStyle adds background color to all the items

If the item is equal or larger than 5 then it should add a blue background all the other items from 1 to 4 should remain transparent but as soon as the counter reaches 5 it makes all the background color blue. https://stackblitz.com/edit/angular-8g4uzm

<button (click)="toggle()">Display Details</button>
    <p *ngIf="show">Secret Password = Tura</p>
    <!-- <ul>
      <li>{{times}}</li>
    </ul> -->
    <p 
    [ngStyle]="{backgroundColor: bgColor() >=5 ? 'blue' : 'transparent'}"
    *ngFor="let logItem of log">{{logItem}}
    </p>

.

 import { Component } from '@angular/core';

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      show = false;
    log=[];
      name = 'Angular';

      toggle() {
        this.show = !this.show;
        this.log.push(this.log.length + 1);
      }

    bgColor() {
    if(this.log.length >=5) {
      return this.log.length
    }
    }

    }

You are checking the length which is increased constantly, so when it reached 5, the condition is true for every line. Replace it with the index:

<p 
   [ngStyle]="{backgroundColor: i >=5 ? 'blue' : 'transparent'}"
   *ngFor="let logItem of log; let i = index">{{logItem}}
</p>

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM