简体   繁体   English

Angular2使用RegExp过滤带有管道的对象数组?

[英]Angular2 Filter Array of Objects with pipe using RegExp?

After hours of searching on stackoverflow and google I did not find what I was searching, I did find something that gave me an idea for an alternative solution. 经过数小时的关于stackoverflow和google的搜索,我没有找到要搜索的内容,但确实找到了一些可以替代解决方案的想法。

Object example: 对象示例:

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"
{    
]

The resolution: 分辨率:

 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> 

This will give me: 这会给我:

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

It works as is, but my intention was to make it work with RegExp, I have tried but for some reason I got an error when I used var something = new RegExp(// some rule). 它按原样工作,但是我的目的是使其与RegExp一起使用,我已经尝试过,但是由于某些原因,当我使用var something = new RegExp(// some rule)时出现错误。

Any idea is much appreciated. 任何想法都非常感谢。

try this 尝试这个

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>

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

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