简体   繁体   English

Angular 7滤镜阵列

[英]Angular 7 filter array

I have the following Angular component: 我有以下Angular组件:

  private json: JsonResponseDTO;

  constructor(private dtoService: PoolDTOServiceService) {
  }

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

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

The json contains an element pools, that is an array. json包含一个元素池,即一个数组。 This one should be filtered by name, which is typed in an input. 此名称应按名称过滤,并在输入中键入。 (I don not show the HTML, since this is not relevant). (我不显示HTML,因为这不相关)。
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);
  }

and then bind the filterJson to the HTML DOM. 然后将filterJson绑定到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. 我想避免每次“删除”过滤后的名称时都请求新的JSON,因为获取数据的时间很昂贵。

You can use a pipe for filtering it will be much cleaner, just add the pipe in front of *ngFor directive. 您可以使用管道进行过滤,它会更清洁,只需将管道添加到* ngFor指令的前面即可。

@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;
  }
}

Add this pipe, and in HTML where ever you need to filter 添加此管道,并在需要过滤的地方添加HTML

<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 希望这会有所帮助

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

You could potentially write it a bit cleaner by using spread and changing the pools property as above. 您可以通过使用spread和如上所述更改pools属性来使其更加简洁。

I'm assuming you should keep a cached copy of the original 'this.json' for a case when the filters are reset. 我假设在重置过滤器的情况下,您应该保留原始“ this.json”的缓存副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM