Red*_*ree 1 javascript css ng-style angular2-directives angular
我正在尝试更改动态添加到元素数组中的元素的背景颜色,点击我在component.html中的第4个按钮,如下所示:
<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>
Run Code Online (Sandbox Code Playgroud)
在第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';
}
}
Run Code Online (Sandbox Code Playgroud)
我在监督什么......?
问题是当你编写<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>
Run Code Online (Sandbox Code Playgroud)
Plunker示例:http://plnkr.co/edit/QECx8Jd2nP8PnrqzcD89?p = preview