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

时间:2019-03-31 23:21:46

标签: angular

我正在在线建立购物网站。我展示了一些衬衫。为了显示它们,我使用了* ngFor循环。现在,我希望当用户单击特定衬衫时,在其下方出现一个新的div,以显示有关该特定衬衫的所有详细信息。我创建了一个onclick函数,该函数将字符串“ shirt(i)”压入数组;然后,我使用* ngIf =“ displayDetails.includes('shirt(i)')”以便在单击衬衫时显示详细信息。但是,它似乎不起作用。

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 个答案:

答案 0 :(得分:0)

我会根据这些建议提出建议

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

}

该集合将强制使用唯一值,并使通过编程更容易地确定其中是否已存在值。