Angular 11中实现ngFor循环内点击图片切换对应详情Div并自动关闭其他已打开详情
解决方案:点击图片时仅显示当前详情,自动关闭其他
我来帮你搞定这个问题!你现在的需求是每次点击图片时,只展示对应项的详情,同时自动关闭之前打开的其他详情区块。这里有两种简单有效的实现方式,你可以根据场景选择:
方法一:重置所有项的显示状态后切换当前项
这种思路很直接:每次点击图片时,先把所有详情统一关闭,再切换当前点击项的显示状态,确保同一时间只有一个详情处于打开状态。
修改后代码:
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { name = 'Angular'; clicked(index) { // 第一步:关闭所有详情 this.things.forEach(item => item.show = false); // 第二步:切换当前点击项的显示状态 this.things[index].show = !this.things[index].show; }; // 注意:给每个对象补上show属性,避免遍历出错 public things:Array<any> = [{ data: "information for img1:", data2: "only the info img1 is displayed", show: false }, { data: "information for img2:", data2: "only the info for img2 is displayed", show: false }, { data: "information for img3:", data2: "only the info for img3 is displayed", show: false }] }
app.component.html(无需修改)
<hello name="{{ name }}"></hello> <h3>How to show info of clicked image only </h3> <div *ngFor="let x of things; let i = index"> <img src="http://lorempixel.com/150/150" alt="loading" (click)="clicked(i)" > <div *ngIf="x.show"> <div class="names"> <div class="fullName">{{x.data}}</div> <div>{{x.data2}}</div> </div> </div> </div>
方法二:维护当前激活的索引(更高效)
这种方法不需要修改每个列表项的属性,而是用一个单独变量记录当前打开项的索引,通过索引匹配控制显示。性能更优,尤其适合数据量较大的场景。
修改后代码:
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { name = 'Angular'; // 初始值设为-1,表示没有激活的项 currentActiveIndex: number = -1; clicked(index) { // 如果点击的是当前激活项,就关闭;否则设置为当前激活项 this.currentActiveIndex = this.currentActiveIndex === index ? -1 : index; }; public things:Array<any> = [{ data: "information for img1:", data2: "only the info img1 is displayed" }, { data: "information for img2:", data2: "only the info for img2 is displayed" }, { data: "information for img3:", data2: "only the info for img3 is displayed" }] }
app.component.html
<hello name="{{ name }}"></hello> <h3>How to show info of clicked image only </h3> <div *ngFor="let x of things; let i = index"> <img src="http://lorempixel.com/150/150" alt="loading" (click)="clicked(i)" > <!-- 改为判断当前索引是否等于激活索引 --> <div *ngIf="currentActiveIndex === i"> <div class="names"> <div class="fullName">{{x.data}}</div> <div>{{x.data2}}</div> </div> </div> </div>
小提示
- 方法一适合需要灵活控制每个项显示状态的场景(比如后续可能需要允许多开);
- 方法二更贴合单一激活的需求,代码更简洁,性能也更好;
- 原代码中
things数组的第三个对象缺少show属性,方法一中需要补上,避免遍历时报错。
内容的提问来源于stack exchange,提问作者uiankosh
相关产品推荐
相关产品推荐

