I'm trying to change the background color of an element dynamically added to the array of elements from the 4th button click on in my component.html like this:
<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>
After the 5th click all elements in the array get the colored background instead of those, which were added after the counter got more than 4. At the same time the ngClass directive works well on the same condition, and only the text in the elements after the 5th click gets white. Here is my 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';
}
}
What am I overseeing ... ?
The problem is when you write <p [ngStyle]="{backgroundColor: blueBackground()}"..
and increment this.counter
, it will effect all the elements because every change detection tick will update all the current elements that have this binding. Hence when the counter is above 4 every element will update itself.
Rather than updating your counter manually you can take advantage of ngFor
's index
property.
Example:
<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 example: http://plnkr.co/edit/QECx8Jd2nP8PnrqzcD89?p=preview