0
votes

I am building a shopping site online. I have a number of shirts displayed. To display them I used *ngFor loop. Now I want that when a user clicks on a specific shirt a new div appears under it showing all the details about that specific shirt. I created an onclick function that pushes into an array a string "shirt(i)"; Then I used *ngIf="displayDetails.includes('shirt(i)')" in order to display the details when the shirt is clicked. However, it doesn't seem to be working.

https://imagizer.imageshack.com/img923/646/JcZR9p.png

//HTML CODE

<div class="products">
  <div class="product" *ngFor="let product of products; let i = index" (click)="showDetails(i)">
    <div class="image">
      <img src='{{ product.image}}'>
    </div>
    <div><h1>{{ product.brand}}</h1></div>
    <div *ngIf="displayDetails.includes('shirt(i)')" class="product-details">
      <h3>Color: {{ product.color }}</h3>
      <h3>Price: {{ product.price}}</h3>
    </div>
  </div>
</div>

//COMPONENT CODE

export class ProductsComponent implements OnInit {

  displayDetails: any[] = [];

  constructor(private http : HttpClient) { }


  showDetails(i){
    this.displayDetails.push("shirt(i)");
    console.log(i);
  }

}
1
Is displayDetails an array of complex objects? If so you cannot use includes() with complex objects, it only works with an array of primitive types. You can use array find() instead with complex objects in an array. - Alexander Staroselsky
No matter what you cannot use includes() or indexOf() on array of objects. - Alexander Staroselsky

1 Answers

1
votes

I would suggest something along these lines

//HTML CODE

<div class="products">
  <div class="product" 
    *ngFor="let product of products; let i = index"
    (click)="toggleItem(i)">

    <div class="image">
      <img src='{{ product.image}}'>
    </div>
    <div><h1>{{ product.brand}}</h1></div>
    <div *ngIf="shouldShowItem(i)" class="product-details">
      <h3>Color: {{ product.color }}</h3>
      <h3>Price: {{ product.price}}</h3>
    </div>
  </div>
</div>

//COMPONENT CODE

export class ProductsComponent implements OnInit {

  displayDetails = new Set<number>();

  constructor(private http : HttpClient) { }

  toggleItem(index: number) {
    if (this.displayDetails.has(index))
      this.displayDetails.delete(index);
    else 
      this.displayDetails.add(index);
  }

  shouldShowItem(i: number) {
    return this.displayDetails.has(i);
  }

}

The set forces unique values, and makes it easier programatically to figure out if there's already a value in there.