Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change a value of element in an ngFor loop

Tags:

angular

ngfor

I have a situation where I am looping over a group of objects and for each object I have a button that when clicked should toggle a variable of isActive to true, but I want this to be specific to just that one element in the loop, currently I can only get it to make all elements active as isActive is component variable.

I created a plunkr in the hope it might help https://plnkr.co/edit/biOfbIjMxjOMUMFWOgyY?p=preview

like image 725
Daimz Avatar asked Mar 10 '23 01:03

Daimz


1 Answers

Instead of introducing a class member to hold the state for each item, you can hold it bound to the item itself. Change the template as following:

  <ul>
    <li *ngFor="let item of list" [ngClass]="{'is-active': item.isActive}">
      <h2>{{ item.title }}</h2>
      <p>{{ item.body }}</p>
      <button (click)="item.isActive = !item.isActive">Toggle active</button>

      <div class="active" *ngIf="item.isActive">
        <small>This should show for only this object in the loop</small>
      </div>
    </li>
  </ul>

No additional setup is required.

like image 116
seidme Avatar answered Mar 21 '23 06:03

seidme