Angular 7滤镜阵列 [英] Angular 7 filter array

查看:37
本文介绍了Angular 7滤镜阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Angular组件:

I have the following Angular component:

  private json: JsonResponseDTO;

  constructor(private dtoService: PoolDTOServiceService) {
  }

  ngOnInit() {
    this.dtoService.setJsonResponse();
    this.getPool();
  }

  getPool() {
    this.json = this.dtoService.jsonResponse;
  }

json 包含一个元素池,即一个数组.此名称应按名称过滤,并在输入中键入.(我不显示HTML,因为这不相关).
我希望能够删除"我的搜索条件,所以最初的方法是:

The json contains an element pools, that is an array. This one should be filtered by name, which is typed in an input. (I don not show the HTML, since this is not relevant).
I want to be able to 'remove' my search criteria, so the initial approach is:

  private json: JsonResponseDTO;
private filterJson: JsonResponseDTO;

  constructor(private dtoService: PoolDTOServiceService) {
  }

  ngOnInit() {
    this.dtoService.setJsonResponse();
    this.getPool();
  }

  getPool() {
    this.json = this.dtoService.jsonResponse;
    this.filterJson = this.json;
  }

  filter(filterCriteria: String) {
    this.filterJson = this.json;
    this.filterJson.pools.filter((element) => element.name === filterCriteria);
  }

,然后将 filterJson 绑定到HTML DOM.
有没有更清洁的方法可以做到这一点?我想避免每次删除"已过滤的名称时都请求新的JSON,因为获取数据的时间很昂贵.

and then bind the filterJson to the HTML DOM.
Is there a cleaner way to do this? I want to avoid requesting the new JSON each time the filtered name is 'removed', since the data is expensive in time to fetch.

推荐答案

您可以使用管道进行过滤,这样会更加清洁,只需将管道添加到* ngFor指令的前面即可.

You can use a pipe for filtering it will be much cleaner, just add the pipe in front of *ngFor directive.

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(value: any, field: string, input: string) {
    if (input !== undefined && input.length >= 2) {
      input = input.toLowerCase();
      if (typeof value[0] === 'string') {
        return value.filter(function(el: any) {
          return el.toLowerCase().indexOf(input) > -1;
        });
      }
      return value.filter(function(el: any) {
        return el[field].toLowerCase().indexOf(input) > -1;
      });
    }
    return value;
  }
}

添加此管道,并在需要过滤的地方添加HTML

Add this pipe, and in HTML where ever you need to filter

<div *ngFor="let val of filterJson | filter: "filterCriteria""> </div>

从变更检测和性能的角度来看,管道很棒.希望这会有所帮助

from change detection and performance point of view, pipes are awesome. Hope this helps, all the best

这篇关于Angular 7滤镜阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆