角形管道,用于使用多级键过滤文本 [英] angular pipe to filter text with multi level key

查看:92
本文介绍了角形管道,用于使用多级键过滤文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个弯角管道,它只是从ngFor过滤掉文本.它与json对象的单个级别一起使用时效果很好,但是在有多个级别的对象时失败.

管道:

 从'@ angular/core'导入{Pipe,PipeTransform};@Pipe({name:'simpleSearch'})导出类SimpleSearchPipe实现了PipeTransform {公共转换(值,键:字符串,术语:字符串){if(!term)返回值;返回(值|| []).filter(item =>keys.split(',').some(key => {item.hasOwnProperty(key)&&新的RegExp(term,'gi').test(item [key])}));}} 

模板:

 < div * ngFor =让issuesData发出|simpleSearch:'key,fields.summary,fields.priority.name':searchTerm></div> 

此处搜索对于字段"key"(json对象的第一级)非常有效,但不适用于其他键.

任何人都可以帮助我解决此问题,或者如果您需要更多信息,请告诉我.

解决方案

尝试使用 lodash STACKBLITZ

I have an angular pipe which just filter outs the text from ngFor. It works very well with single level of json object but fails when there is multi level object.

Pipe:

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

@Pipe({   name: 'simpleSearch' })
  export class SimpleSearchPipe implements PipeTransform {

  public transform(value, keys: string, term: string) {

    if (!term) return value;
    return (value || [])
        .filter(item => 
             keys.split(',').some(key => {
                item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])
             })
        );
   }
}

template:

<div *ngFor="let issue of issuesData
      | simpleSearch: 'key,fields.summary,fields.priority.name': searchTerm"
></div>

Here the search works very well for the field "key" (1st level of json object) but doesn't works for other keys.

Can anyone please help me fix this or please let me know if you need some more info.

解决方案

try to use lodash's get() function:

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

import * as lodash from 'lodash';

@Pipe({ name: 'simpleSearch' })
export class SimpleSearchPipe implements PipeTransform {

  public transform(value, keys: string, term: string) {

    if (!term) return value;
    return (value || [])
      .filter(item =>
        keys.split(',').some(key => {
          const val = lodash.get(item, key, undefined);
          return val !== undefined && new RegExp(term, 'gi').test(val);
        })
      );
  }
}

also, in your some() function you need to return boolean by providing return statement or by removing curly brackets. I added return in your code.

STACKBLITZ

这篇关于角形管道,用于使用多级键过滤文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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