【问题标题】:How do I get a number of items in a filtered list?如何在过滤列表中获取多个项目?
【发布时间】:2017-03-18 09:44:37
【问题描述】:

所以,我有一个过滤管道并使用它来过滤城市列表以仅显示包含搜索词的城市。

import {Pipe, PipeTransform} from '@angular/core';

    @Pipe({ name: 'filter' })
    export class FilterPipe implements PipeTransform{
        transform(value: any, arg: string) {
            var searchTerm = arg ? arg : '';
            searchTerm = searchTerm.toUpperCase();
            if (value == null) return null;
            return value.filter(el => el.City.toUpperCase().indexOf(searchTerm) !== -1);
        }
    }

但我拥有的城市数组中有 5000 个项目,因此我使用切片管道仅显示其中五个。

<form [formGroup]="form">
  <input formControlName="search" type="text">
  <div>
    <li 
    *ngFor="let city of cities | filter:searchTerm | slice:0:5"
    (click)="PasteCity(city.City)">
      {{ city.City }}
    </li>
  </div>
</form>

但是有一个问题。我需要向用户显示找到了多少个城市,例如“显示 5 0f 631 个城市”。 据我尝试,ViewChildren 和索引*ngFor 方法的最后一个元素只让我得到了显示的城市数量,没有被过滤器找到......但是在尝试使用ViewChildren 时我遇到了一个错误并很快被刮掉了这个想法

【问题讨论】:

  • 你应该使用指令而不是管道
  • 我正在寻找一种方法,但是我发现的所有过滤方法都是使用管道进行的,您能解释一下您建议的方法吗?

标签: angular pipe filtering


【解决方案1】:

你试过了吗

(cities | filter:searchTerm).length 

?

【讨论】:

  • 我需要在数组通过切片管道之前知道长度,所以,当我侦察时,你的代码会给我 5 或更少,但事实并非如此
  • 成功了!我在
  • 元素之后添加了 '{{ (cities | filter:searchTerm)?.length }}'!非常感谢你!荣誉
猜你喜欢
相关资源
最近更新 更多
热门标签