【发布时间】:2017-10-18 19:20:35
【问题描述】:
我正在尝试更改从第 4 个按钮单击我的 component.html 中动态添加到元素数组的元素的背景颜色,如下所示:
<button class="btn" (click)="toggleContent()">Display Details</button>
<div class="left-align left-div">
<div class="center-align" *ngFor="let counter of count" >
<p [ngStyle]="{backgroundColor: blueBackground()}" [ngClass]="{whitetext: counter > 4}">{{ counter }}</p>
</div>
</div>
在第 5 次单击后,数组中的所有元素都会获得彩色背景,而不是那些在计数器超过 4 后添加的元素。同时 ngClass 指令在相同条件下运行良好,只有文本第 5 次单击后的元素变为白色。这是我的component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styles: [`
.outer-div {
height: 20px;
margin: 20px;
}
.left-div {
width: 50px;
margin-top: 5px;
}
.inner-div {
border: 2px solid lightblue;
height: 20px;
margin: 20px;
}
.whitetext {
color: white;
}
`]
})
export class AppComponent {
count = [];
counter: number = 0;
toggleContent() {
this.counter ++;
this.count.push(this.counter);
}
blueBackground() {
return (this.counter > 4) ? 'lightblue' : 'white';
}
}
我在监督什么……?
【问题讨论】:
-
所以你只想要第 5 个元素的蓝色背景?
-
是的,从第五个元素开始的所有后续元素。
标签: javascript css angular angular2-directives ng-style