1

I'm trying to use ngClass to add a class on any span elements after the fourth one is added to the DOM (happens via a button click that increments a counter variable and also toggles the visibility of a paragraph), but I don't know how to make this to where any of the first four spans do not also get this class added once the fifth one is reached. I feel like this is easy to accomplish, but I'm stuck.

I tried adding an index to the *ngFor and then adding the class based on the index but that produced the same result.

Template:

<p *ngFor="let click of buttonClicks;">
    <span [ngClass]="{ 'white': counter > 4 }">{{ [click] }}</span>
</p>

<button (click)="displayDetails()">Display Details</button>

<p *ngIf="detailsVisible">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Doloribus quasi id, molestiae doloremque alias non adipisci placeat corrupti commodi minus voluptas debitis eaque iure obcaecati minima neque et molestias atque.</p>

Component:

export class AppComponent {

    detailsVisible: boolean = false;

    buttonClicks: Array<number> = [];
    counter: number = 0;

    displayDetails() {
      this.detailsVisible = !this.detailsVisible;
      this.buttonClicks.push(this.counter);
      this.counter++; 
    }
}

1 Answer 1

2

You don't need any counter. You need the index of each span:

<p *ngFor="let click of buttonClicks; index as i">
  <span [ngClass]="{ 'white': i > 4 }">{{ [click] }}</span>
</p>

Or, since the value of click is the index, you can just use its value:

<p *ngFor="let click of buttonClicks">
  <span [ngClass]="{ 'white': click > 4 }">{{ [click] }}</span>
</p>
Sign up to request clarification or add additional context in comments.

1 Comment

Weird. I swear I tried exactly this using an index value but it was producing the same result. Maybe the page hadn't updated for some reason. But thanks so much for the reply, I'll mark this as correct once I'm able to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.