Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

angular11 - 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?

question from:https://stackoverflow.com/questions/65897423/angular-toggle-only-selected-item

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...