【问题标题】:Angular2 Filter Array of Objects with pipe using RegExp?Angular2使用RegExp过滤带有管道的对象数组?
【发布时间】:2017-03-25 19:18:09
【问题描述】:

在 stackoverflow 和谷歌上搜索了几个小时后,我没有找到我正在搜索的内容,但我确实找到了一些让我想到替代解决方案的东西。

对象示例:

items = [
{
    title: "This is title", 
    email: "test@test.com",
    status: "confirmed"
},
{
    title: "This another one", 
    email: "someone@something.com",
    status: "pending"
{    
    title: "Just a random string", 
    email: "me@you.co.uk",
    status: "pending"
{    
]

分辨率:

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

@Pipe({
  name: 'filter',
  pure: false
})
export class FilterPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    if(args == '') { return value; }

    let query = args.toLowerCase();
    return value.filter(task =>
      task.title.toLowerCase().indexOf(query) > -1 ||
      task.email.toLowerCase().indexOf(query) > -1 ||
      task.status.toLowerCase().indexOf(query) > -1 

    );
    
  }
}

<div *ngFor="item of (items | filter:'this is') ">
   {{item | json}}
 </div>

这会给我:

{title: "This is title", email: "test@test.com",status: "confirmed"}

它按原样工作,但我的意图是让它与 RegExp 一起工作,我已经尝试过,但由于某种原因,当我使用 var something = new RegExp(// some rule) 时出现错误。

非常感谢任何想法。

【问题讨论】:

  • 你遇到了什么错误?
  • 新的东西不是函数。

标签: javascript angular angular2-pipe


【解决方案1】:

试试这个

import {Pipe} from 'angular2/core';

// Tell Angular2 we're creating a Pipe with TypeScript decorators
@Pipe({
  name: 'RegexPipe'
})
export class RegexPipe {

  transform(value, args?) {
    // ES6 array destructuring
    let [pattern] = args;
    return value.filter(task => {
        reg = new Regex(pattern);
        found = reg.test(task.title);
      return found;
    });
  }

}

<div *ngFor="item of (items | RegexPipe:'/this is (.)*/') ">
   {{item | json}}
 </div>

【讨论】:

    猜你喜欢
    • 2017-06-21
    • 2016-05-12
    • 1970-01-01
    • 2023-03-14
    • 2017-05-13
    • 2017-12-02
    • 2018-05-09
    • 2021-01-27
    • 2018-03-12
    相关资源
    最近更新 更多