【发布时间】:2021-09-09 14:18:53
【问题描述】:
我有多个包含信息图像和详细信息的部分,当我单击信息图像时,特定详细信息应该切换。所有图像和 div 都在循环内。一切正常,但是当我单击另一个图像而不关闭以前的详细信息时,它保持打开状态。当我单击其他图像时,上一部分应该关闭。这是下面的代码 https://stackblitz.com/edit/angular-nrys31?file=src%2Fapp%2Fapp.component.html
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';
public show:boolean = false;
clicked(index) {// only show clicked img info
console.log(this.things[index]);
this.things[index].show = !this.things[index].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"
},
{
data: "information for img3:",
data2: "only the info for img3 is displayed"
}]
}
【问题讨论】:
-
您可以在类级别获取一个变量并将索引存储在那里。每当单击一个块时,关闭上一个打开的块并将上一个更新为新的。
-
已经再次使用 ngif 为什么我们需要类来隐藏它
-
最后点击图片的show属性需要更新为false,同时将当前点击图片的show属性设置为true。
标签: javascript html angular