When I click on a button, I am adding strings to an array and I need to show these strings in a page. But I need to show the text red only after 5th element (first 5 elements should have the text black). Here is what I've tried:
the component code:
import { Component } from '@angular/core';
@Component({
selector : 'app-toggle',
templateUrl : './toggle.component.html',
styleUrls : ['./toggle.component.css']
})
export class ToggleComponent {
toggleState = false;
clickNumber = 0;
actions = [];
action = 'Display';
onClick() {
this.clickNumber++;
this.toggleState = !this.toggleState;
if (this.toggleState) {
this.action = 'Display';
} else {
this.action = 'Hide';
}
this.actions.push('click number: ' + this.clickNumber.toString() + ', changed the state to ' + this.action);
}
getColor(): string {
if (this.clickNumber > 5) {
return 'red';
} else {
return 'black';
}
}
}
and the html code:
<button (click)="onClick()" >{{action}} details</button>
<p *ngIf="toggleState">Password details: secret</p>
<p *ngFor="let act of actions" [ngStyle]="{'color' : getColor()}">{{act}}</p>
but my problem is that after I click more that 5 times, all the paragraph elements change the text color. So how to achieve this? What I've done wrong? I am using angular 6.
Here is how my page looks:
You can use the index property of *ngFor
, along with ngStyle
like so:
<p *ngFor="let act of actions; let i = index" [ngStyle]="{'color' : i > 5 ? 'red' : 'black'}">{{act}}</p>
Use the ngStyle with the condition >5
<p *ngFor="let act of actions; let i = index" [ngStyle]="{'color' : i > 5 ? 'red' : 'black'}">{{act}}</p>
If I may suggest a much easier css solution, using nth-child
p:nth-child(n+6) {
color: red;
}
<p>
Foo
</p>
<p>
Foo
</p>
<p>
Foo
</p>
<p>
Foo
</p>
<p>
Foo
</p>
<p>
Foo
</p>
<p>
Foo
</p>
<p>
Foo
</p>
Fix - 1 : Modify getColor() function
Pass the current index value, otherwise the clicknumber will be same for all the elements when it is 6
getColor(current): string {
if (current > 5) {
return 'red';
} else {
return 'black';
}
}
HTML
<button (click)="onClick()" >{{action}} details</button>
<p *ngIf="toggleState">Password details: secret</p>
<p *ngFor="let act of actions;let i = index" [ngStyle]="{'color' : getColor(i)}">{{act}}</p>
Working example : stackblitz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With