首页 > 解决方案 > ngFor 过滤器在子组件中返回 no items 消息

问题描述

我有一个包含子组件集合的父集合。

[parent]
 [child]
 [child]
[parent]
 [child]

我在 ngFor 上为孩子们设置了一个过滤器,

当我过滤时,它会过滤数据,但我的视图最终看起来像这样:

[parent]
[parent]
 [child]

如果孩子没有物品,是否有办法过滤掉父母?或者,让它做这样的事情:

[parent]
 No Items Found!
[parent]
 [child]

感谢您的帮助,刚刚学习 Angular 7。

html:

    <div style="margin-top: 30px;">
  <div *ngFor="let organization of column.boardColumnWorkItems">
    <div class="row">
      <div class="col-sm-4 organization-row">
        {{organization.name}}
      </div>
    </div>
    <app-board-column-tile *ngFor="let workItem of organization.workItems | workItemFilter:filterTerm"
                           [boardColumnWorkItem]="workItem">
    </app-board-column-tile>
  </div>
</div>

过滤器/管道:

transform(workItems: any, filterTerm: any): any {
console.log("WorkItemFilterPipe: " + filterTerm);
//Check if filter term is undefined
if (filterTerm === undefined)
  return workItems;
//Return the filtered list of workitems
this.filteredWorkItems = workItems.filter(function (workItem) {
  return workItem.filterData.includes(filterTerm.toLowerCase());
})

console.log(this.filteredWorkItems.length);

return this.filteredWorkItems;

}

标签: angularfilterparent-childngforchildren

解决方案


您可以尝试如下:

<ng-container *ngIf="organization.workItems | workItemFilter:filterTerm as filteredWorkItems">
  <app-board-column-tile *ngFor="let workItem of filteredWorkItems"
                           [boardColumnWorkItem]="workItem">
  </app-board-column-tile>
  <h3 *ngIf="filteredWorkItems.length === 0">No filtered results!</h3>
</ng-container>

推荐阅读