Daimz
Daimz

Reputation: 3281

Change a value of element in an ngFor loop

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

Upvotes: 5

Views: 8318

Answers (1)

seidme
seidme

Reputation: 13048

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.

Upvotes: 8

Related Questions