Search code examples
javascriptangulartypescriptng-style

angular: set different color to paragraphs with ngFor


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:

enter image description here


Solution

  • 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>