Rajat Singh
Rajat Singh

Reputation: 703

How to change Class of a div using on click of using ngClass

I have a button tag, upon clicking on what, it should change the class of a div tag.I'm using ngFor, so each row should be treated individually.

Here's the snippet of my code and what I want to do.

  <div *ngFor="let item of users">
  <button class="fas fa-angle-up"></button>
  <strong>NAME </strong>{{item.attribute.name}}
  <div class="pf-m-expanded">Some Content Here</div> <!--This is the class that has to toggle upon clicking that **button**>
  </div>

What I want to do is upon clicking the button, I should be able to toggle(remove and activate class) pf-m-expanded. And since it is a *ngFor, It should treat each row individually.

Upvotes: 0

Views: 647

Answers (1)

David
David

Reputation: 147

You can define a local variable inside the loop, and have the button to toggle the value of the variable, then have [ngClass] to add/remove the class based on the value of the variable.

<div *ngFor="let item of users; let toggle = true;">
  <button class="fas fa-angle-up" (click)="toggle = !toggle">Test</button>
  <strong>NAME </strong>{{item.attribute.name}}
  <div [ngClass]="{ 'pf-m-expanded': toggle }">
    Some Content Here
  </div>
</div>

Upvotes: 1

Related Questions