在Angular2中,如何检测过滤器/管道没有返回任何结果

时间:2016-11-12 15:21:16

标签: angular

我希望在过滤器返回空数组时显示一条消息,例如“没有找到结果”

这是我的带有过滤器的ngFor列表

 <li class="col-xs-12" *ngFor="let item of jobs | jobsFilter: [originalJobList, region, county, type]"></li>

<p>No results found</p>

如果没有过滤器,它很容易,但因为过滤器我不知道怎么说过滤器没有返回结果。

这是我的过滤器:

import { Pipe } from "@angular/core";

@Pipe({
  name: 'jobsFilter',
  pure: true
})

export class JobsFilter {
   transform(items: any, [originalList, region, county, type]: any) {
      //Filter options:
        var overallResults = originalList;
        var filterByRegion = false;
        var filterByCounty = false;
        var filterByType = false;

        if (region !== "Filter by Region") filterByRegion = true;

        if (county !== "Filter by County") filterByCounty = true;

        if (type !== "Filter by Type") filterByType = true;

        if (filterByType) overallResults = overallResults.filter(item => item.type === type);

        if (filterByRegion) overallResults = overallResults.filter(item => item.region === region);

        if (filterByCounty) overallResults = overallResults.filter(item => item.county === county);

        return overallResults;
  }
}
  

这一切都有效,但我只需要向用户显示过滤器   使用消息而不是空屏幕返回无结果。

2 个答案:

答案 0 :(得分:1)

<li class="col-xs-12" *ngFor="let item of jobs | jobsFilter: [originalJobList, region, county, type]"></li>

<p *ngIf="!(jobs | jobsFilter: [originalJobList, region, county, type]?.length)">No results found</p>

答案 1 :(得分:0)

阅读以下文章:

https://netbasal.com/using-pipe-results-in-angular-templates-430683fa2213

摘要:

<ng-container *ngIf=”(items | filter:search.value) as result”>

  <div *ngFor=”let item of result”>
    {{item}}
  </div>

  <p>Count: <b>{{result.length}}</b></p>

</ng-container>