简体   繁体   English

为什么此ngStyle会为所有项目添加背景色

[英]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. 如果项目等于或大于5,则应添加蓝色背景,所有其他项目(从1到4)应保持透明,但一旦计数器达到5,它将使所有背景颜色变为蓝色。 https://stackblitz.com/edit/angular-8g4uzm 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. 您正在检查不断增加的长度,因此当长度达到5时,每一行的条件都成立。 Replace it with the index: 将其替换为索引:

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

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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