Search code examples
angularangular11

Angular toggle only selected item


I have a list that's created dynamically. Each item in the list will toggle when clicked.

Here is the .html code:

<ul *ngFor="let item of items">
    <li (click)="toggle($event)">{{text}}</li>
</ul>

And the .ts code:

toggle(event) {
    this.visible = !this.visible;
}

At the moment when I click on an item all the items in the list will toggle.

How can I change it so that only the clicked item will toggle?


Solution

  • I think this is not "toggle" situation, because how can you click something once it's invisible?

    Anyway, you can make every <li> as component and than every visible will be in a different scope. Another way, you can add to item object a property, for example visible and then every click will change the value as you want.

    For example:

    <ul *ngFor="let item of items">
        <li *ngIf="item.visible" (click)="item.visible = false">{{item.text}}</li>
    </ul>