【问题标题】:angular "*ngIf" inside "*ngFor" not working?“*ngFor”中的角度“*ngIf”不起作用?
【发布时间】:2019-08-22 02:26:23
【问题描述】:

我正在建立一个在线购物网站。我展示了许多衬衫。为了显示它们,我使用了 *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);
  }

}

【问题讨论】:

  • displayDetails 是复杂对象的数组吗?如果是这样,您不能将 includes() 用于复杂对象,它仅适用于原始类型数组。您可以使用数组 find() 代替数组中的复杂对象。
  • 无论你不能在对象数组上使用 include() 或 indexOf()。

标签: angular


【解决方案1】:

我会建议一些类似的东西

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

}

该集合强制使用唯一值,并以编程方式更容易确定其中是否已经存在值。

【讨论】:

  • 谢谢!你能解释一下为什么我的代码不起作用吗?
  • displayDetails.includes('shirt(i)') 此处的代码检查字符串是否包含“shirt(i)”(实际上是 shirt i,而不是您定义的函数)。您想要的是在索引中进行函数调用,但您所做的是检查数组中的“shirt(i)”
猜你喜欢
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 2017-02-23
  • 2020-11-15
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
  • 2018-10-22
相关资源
最近更新 更多