2016-11-11 13 views
0

私は何を探していたのかわからなかったので、stackoverflowとgoogleで何時間も検索したところ、別の解決方法が見つかった。RegExpを使用するパイプを持つオブジェクトのAngular2フィルタ配列?

オブジェクト例:

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>