【问题标题】:How to hide a category when there are no items in it?没有项目时如何隐藏类别?
【发布时间】:2020-11-05 09:12:57
【问题描述】:

我的 Angular 应用程序中有两个数组,一个是包含类别的对象数组,另一个是包含项目的数组,其中有一个对象属性,表示项目属于哪个类别。

所以我制作了一些自定义管道,如果选择“全部”类别,则返回所有项目,另外两个管道用于项目数组,返回每个类别的过滤项目,另一个管道用于搜索。

选择“ all”时,这些项目用类别名称渲染,但是当我搜索一个项目时,如果没有项目,我会隐藏类别标签。

我该如何存档?

这是我的*ngFor,我正在渲染这些东西:

<div
   *ngFor="
   let cat of category
   | menuFiltered
   : (selected === -1 ? -1 : category[selected].id)
   "
   class="products"
   >
   <h2>{{ category.desc }}</h2> // i need to hide this if the below plus array in search is empty
   <hr />
   <div
      *ngFor="
      let plu of plus
      | pluFiltered: men.id
      | pluSearch: searchModel
      "
      class="row mb-3 product"
      >
      ...
   </div>
</div>

编辑: 数组如下所示:

menu = [{id: 123, codmen: 2, desc: "ANTIPASTI", estesa: ""}, {id: 127, codmen: 5, desc: "PRIMI", estesa: ""}, {id: 128, codmen: 6, desc: "SECONDI", estesa: ""}] // this is the "category"

plus = [{desc: "SFOGLIATINA AL CARTOCCIO", menu: 123}, {desc: "SFOGLIATINA AL CARTOCCIO", menu: 127}, {desc: "SFOGLIATINA AL CARTOCCIO", menu: 128}] // menu is the actualy id of menu array to which item belong

一旦我从我的 API 中获取项目,我将从菜单数组中删除所有没有任何项目的对象,如下所示:

this.menu = this.menu.filter((menu) =>
  this.plus.some((item) => item.menu === menu.id)
);

这是我的管道:

menuFiltered管道:

export class MenuFilteredPipe implements PipeTransform {

  transform(list: any[], menu: number): any {
    return list ? menu === -1 ? list : list.filter(item => item.id === menu) : [];
  }

}

pluFiltered管道:

export class PluFilteredPipe implements PipeTransform {

  transform(list: any[], menu: number): any {
    return list ? list.filter(item => item.menu === menu) : [];
  }
}

还有pluSearch 管道:

export class PluSearchPipe implements PipeTransform {

  transform(list: any[], filterText: string): any {

    return list ? list.filter(item => item.desc.search(new RegExp(filterText, 'i')) > -1) : [];

  }

}

【问题讨论】:

  • 您的问题似乎有XY Problem。请尝试发布有问题的数组和管道,而不是尝试解决它。​​
  • @MichaelD 添加了我的管道和数组

标签: javascript angular


【解决方案1】:

尝试使用带有 *ngIf 的 ng 容器:

<div
 *ngFor="let cat of category| menuFiltered: (selected === -1 ? -1 : category[selected].id)" class="products">
  <ng-container *ngIf="plus | pluFiltered: men.id | pluSearch: searchModel as plusArray">
    <h2 *ngIf="plusArray.length > 0">{{ category.desc }}</h2>
     <div *ngFor="let plu of plusArray" class="row mb-3 product">
       ...
     </div>
  </ng-container>
</div>

【讨论】:

  • 我实际上还在使用 ng-container 来显示这样的骨架:&lt;ng-container *ngIf=" plus.length else skeletonTemplate " &gt; 您的解决方案正在运行,但我如何在同一个 *ngIF 中仍然使用 plus.length else skeletonTemplate
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-24
相关资源
最近更新 更多