Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 521
Buda Gavril Avatar asked Jul 08 '18 17:07

Buda Gavril


4 Answers

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>
like image 57
user184994 Avatar answered Oct 05 '22 02:10

user184994


Use the ngStyle with the condition >5

<p *ngFor="let act of actions; let i = index" [ngStyle]="{'color' : i > 5 ? 'red' : 'black'}">{{act}}</p>
like image 38
Sajeetharan Avatar answered Oct 05 '22 00:10

Sajeetharan


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>
like image 37
baao Avatar answered Oct 05 '22 00:10

baao


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

like image 28
Debojyoti Avatar answered Oct 05 '22 01:10

Debojyoti