2016-11-11 49 views
0

經過幾個小時的搜索stackoverflow和谷歌我沒有找到我正在尋找什麼,我找到了一些讓我有一個替代解決方案的想法。Angular2使用RegExp過濾管道對象數組?

對象例如:

items = [ 
{ 
    title: "This is title", 
    email: "[email protected]", 
    status: "confirmed" 
}, 
{ 
    title: "This another one", 
    email: "[email protected]", 
    status: "pending" 
{  
    title: "Just a random string", 
    email: "[email protected]", 
    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: "[email protected]",status: "confirmed"} 

它的工作原理是,但我的意圖是使之與正則表達式的工作,我都試過,但由於某種原因,當我使用VAR東西,我得到了一個錯誤=新的RegExp(//一些規則)。

任何想法是非常感激。

+0

你得到什麼錯誤? –

+0

新事物不是功能。 –

回答

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> 
相關問題