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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With