在 Angular 中制作动态过滤器

make a dynamic filter in Angular

我有一个管道,可以跨组件重复使用。通常在搜索时。

HTML 看起来像这样,您可以看到我有一个包含 "plantNumber" 和 "shortDescription" 的数组,但它可能是无穷无尽的属性列表

*ngFor="let workOrder of workOrders | filterArrayPipe: ['plantNumber', 'shortDescription']: searchFilter"

过滤器看起来像这样

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

@Pipe({
  name: 'filterArrayPipe'
})
export class FilterArrayPipe implements PipeTransform {
  transform(value: any, config: any, q: string) {
    if (config && q) {
      return value.filter(result => {
        return result[config[0]].toString().toLowerCase().indexOf(q) > -1 
          || result[config[1]].toString().toLowerCase().indexOf(q) > -1;
      });
    } else {
      return value;
    }
  }
}

但我希望它看起来更像这样

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

@Pipe({
  name: 'filterArrayPipe'
})
export class FilterArrayPipe implements PipeTransform {
  transform(value: any, config: any, q: string) {
    if (config && q) {
      return value.filter(result => {
        for (let i = 0; i < config.length; i ++) {
          const type = config[i];
          return result[type].toString().toLowerCase().indexOf(q) > -1;
        }
      });
    } else {
      return value;
    }
  }
}

所以问题是,我将如何添加 "and"||在 return 语句中 ?

由于 return 在那个 for 循环中,它只会检查第一个 config 项。

相反,您可以执行以下操作:

  return value.filter(result => {
    for (let i = 0; i < config.length; i ++) {
      const type = config[i];
      if (result[type].toString().toLowerCase().indexOf(q) > -1) {
        return true;
      }
    }
    return false;
  });

这样,它将尝试 config 数组中的每个值,只有 return false 如果找不到匹配项。

或者,使用 some 函数,您可以执行以下操作:

  return value.filter(result => {
    return config.some((type) => result[type].toString().toLowerCase().indexOf(q) > -1)
  });