【发布时间】:2021-10-13 03:08:29
【问题描述】:
我有一些图像和信息文本,所以当我点击图像时,特定的信息文本用于切换/显示。此外,如果以前的信息文本被打开,这将隐藏,下一个信息文本将在单击任何其他图像时显示。现在我的要求是关闭外部的信息文本,如果它打开的话。这是下面的代码。 https://stackblitz.com/edit/angular-mb2rmb?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="https://source.unsplash.com/200x200"
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,Renderer2,ElementRef,ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular';
previousIndex: number = -1;
public show: boolean = false;
@ViewChild('toggleButton') toggleButton: ElementRef;
@ViewChild('menu') menu: ElementRef;
clicked(index) {
// Checking if same picture clicked or new
if (this.previousIndex >= 0 && this.previousIndex != index) {
// If new picture is clicked then closing previous picture
this.things[this.previousIndex].show = false;
}
// Updating index
this.previousIndex = 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',
show: false,
},
{
data: 'information for img3:',
data2: 'only the info for img3 is displayed',
show: false,
},
];
}
【问题讨论】:
-
ng-click-outside效果很好。你只需要html, body { min-height: 100%; }就可以让它在任何地方都能正常工作。
标签: javascript angular