如果项目等于或大于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>