简体   繁体   English

“ * ngFor”内的角度“ * ngIf”不起作用?

[英]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. 为了显示它们,我使用了* ngFor循环。 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. 现在,我希望当用户单击特定衬衫时,在其下方出现一个新的div,以显示有关该特定衬衫的所有详细信息。 I created an onclick function that pushes into an array a string "shirt(i)"; 我创建了一个onclick函数,该函数将字符串“ shirt(i)”压入数组; Then I used *ngIf="displayDetails.includes('shirt(i)')" in order to display the details when the shirt is clicked. 然后,我使用* ngIf =“ displayDetails.includes('shirt(i)')”以便在单击衬衫时显示详细信息。 However, it doesn't seem to be working. 但是,它似乎不起作用。

https://imagizer.imageshack.com/img923/646/JcZR9p.png 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);
  }

}

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. 该集合将强制使用唯一值,并使通过编程更容易地确定其中是否已存在值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM