[英]Why does this ngStyle adds background color to all the items
如果項目等於或大於5,則應添加藍色背景,所有其他項目(從1到4)應保持透明,但一旦計數器達到5,它將使所有背景顏色變為藍色。 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
}
}
}
您正在檢查不斷增加的長度,因此當長度達到5時,每一行的條件都成立。 將其替換為索引:
<p
[ngStyle]="{backgroundColor: i >=5 ? 'blue' : 'transparent'}"
*ngFor="let logItem of log; let i = index">{{logItem}}
</p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.