Home > Back-end >  ngFor click only one item
ngFor click only one item

Time:12-27

I have a problem with the ngFor: for each item in the list I have an image and by clicking I would like to show the details of only that image. The problem is that if I click on an image, the details of all the items in the list come out.

.html:

  <div  *ngFor="let r of result">
    <img [src]="r.images.downsized.url" alt="image" (click)="getDetails()">
    <div  *ngIf="this.clicked">
      <ion-list>
        <ion-item>
          <ion-label>
            <h2>username: {{r?.username}}</h2>
            <h3>title: {{r?.title}}</h3>
            <p>import date:{{r?.import_datetime}}</p>
          </ion-label>
        </ion-item>
      </ion-list>
    </div>
  </div>

.ts:

  ngOnInit() {
    this.clicked = false
  }

  getDetails(): void {
    if (!this.clicked) {
      this.clicked = true
    }
    else {
      this.clicked = false
    }
  }

CodePudding user response:

this in your case is component instance, so this.clicked is global for all your iterated items, that is why all of them get shown. As one solution you can store clicked index:

<div  *ngFor="let r of result; let i = index">
<img [src]="r.images.downsized.url" alt="image" (click)="clickedIndex = i">
<div  *ngIf="clickedIndex === i">
  <ion-list>
    <ion-item>
      <ion-label>
        <h2>username: {{r?.username}}</h2>
        <h3>title: {{r?.title}}</h3>
        <p>import date:{{r?.import_datetime}}</p>
      </ion-label>
    </ion-item>
  </ion-list>
</div>

Another solution would be to move details section from the loop into separate component, which will receive details as @Input

CodePudding user response:

The this refers to the whole component. Alas there is only one this.clicked.

Change (click)="getDetails()" to something like (click)="getDetails(r)" and
getDetails(): void { to something like getDetails(r: TypeOfR): void { and keep an array or hashmap with clicked Rs.

  • Related