Daniel Krieger
Daniel Krieger

Reputation: 35

angular "*ngIf" inside "*ngFor" not working?

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);
  }

}

Upvotes: 0

Views: 1103

Answers (1)

Rachael Dawn
Rachael Dawn

Reputation: 899

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.

Upvotes: 2

Related Questions