首页 > 解决方案 > 没有项目时如何隐藏类别?

问题描述

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

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

The items are rendered with category name when "all" is selected but when i'm searching for an item i would hide the category label if there are no items it it.

我怎么存档呢?

这是我*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) : [];

  }

}

标签: javascriptangular

解决方案


尝试使用带有 *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>

推荐阅读