我正在尝试从组件中的第 4 个按钮单击动态添加到元素数组中的元素的背景颜色.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 次单击后元素中的文本变为白色。这是我的组件.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';
}
}
我在监督什么... ?
问题是当你编写<p [ngStyle]="{backgroundColor: blueBackground()}"..
并递增this.counter
时,它会影响所有元素,因为每个更改检测时钟周期都会更新所有具有此绑定的当前元素。因此,当计数器高于 4 时,每个元素都会自行更新。
与其手动更新计数器,不如利用ngFor
index
属性。
例:
<div class="center-align" *ngFor="let counter of count;let i = index" >
<p [ngStyle]="{'backgroundColor': (i+1 > 4) ? 'lightblue' : 'white'}" [ngClass]="{whitetext: counter > 4}">{{ counter }}</p>
</div>
Plunker示例:http://plnkr.co/edit/QECx8Jd2nP8PnrqzcD89?p=preview