I have multiple sections that contains info image and the details , when I click the info image specific details should toggle. All the images and divs are inside loop. Every thing is working fine but when I click another image without closing previous details, it keeps remain open. Previous section should close when I click on other image. Here is the code below https://stackblitz.com/edit/angular-nrys31?file=src%2Fapp%2Fapp.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>
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"
}]
}
Whenever you click on any image you're toggling the show property of that image only.
this.things[index].show = !this.things[index].show;
This means that if any previous image is opened it will stay open alongside other images.
To solve this problem you have to create a variable that will hold an index of the clicked image and will use to set show property of the image to false whenever a new image will be clicked.
Solution
Create Variable:
previousIndex: number = -1;Update clicked function
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;
}
you ca use angular services to store things :
and use properties like data and should_hide
@Injectable({
providedIn: 'root'
})
export class YourServiceService {
constructor( ) {
this.things = [
{ data: "yourData1", should_hide: false },
{ data: "yourData2", should_hide: true },
]
and toggle it based on should_hide in ngif inside ngfor
Here is updated stackblitz
https://stackblitz.com/edit/angular-ozjttg?file=src%2Fapp%2Fapp.component.ts