2016-07-31 65 views
0

我有多個不同的管道,如果用戶想要通過一些不同的標準過濾他們的數據,我想打開和關閉。我將如何激活/停用搜索中當前使用的管道,或者根據用戶點擊的按鈕來構建行爲不同的單個管道?Angular 2,根據用戶偏好動態構建一個自定義管道

例如兩個管道/過濾器應該是這樣的......

//cloud.pipe.ts 
import {Pipe} from '@angular/core'; 
import {Hero} from './hero'; 

@Pipe({ 
    name: 'Cloud' 
}) 
export class CloudPipe{ 
    transform(value) { 
    if (value == null) { 
     return null; 
    } 
    return value.filter(hero => { 
     return hero.cloud === true; 
    }); 
    } 
} 
//location.pipe.ts 
import {Pipe} from '@angular/core'; 
import {Hero} from './hero'; 
import { HeroService } from './hero.service'; 
import { HeroesComponent } from './heroes.component'; 

@Pipe({ 
    name: 'Location' 
}) 

export class LocationPipe{ 
    transform(value) { 
    if (value == null) { 
     return null; 
    } 
    return value.filter(hero => { 
     return hero.location < 500; 
    }); 
    } 
} 

然後我想有用戶切換不同的過濾器按鈕,並添加/刪除管到列表中。什麼是這樣的最好的方法?

<!--Toggle what pipes should be used in search--> 
<!--For example how can I construct the "updatePipe" function for doing this?--> 
<button id="activateCloud" (click)="updatePipe()"></button> 
<button id="activateLocation" (click)="updatePipe()"></button> 
<!--Is it possible to have: neither of the pipes active, both at the same time or just one at the time? How can I do this?--> 
<div *ngFor="let hero of heroes | Cloud | Location ></div> 

我寧願沒有在同一個管道中的所有東西,因爲我希望將每個管道擴展到將來做更多。所以每根管子都應該是「自己的」,並且彼此獨立工作,但同時必要時與其他管道一起工作。

回答

0

你可以創建轉發依賴於參數的其它管一樣

<div *ngFor="let hero of heroes | myPipe:'Cloud':'Location'" ></div> 
@Pipe({ 
    name: 'myPipe' 
}) 
export class MyPipe{ 
    locationPipe = new LocationPipe(); 
    cloudPipe = new CloudPipe(); 
    constructor() { 
    pipes = { 
     locationPipe: this.locationPipe, 
     cloudPipe: this.clouldPipe 
    }; 
    } 

    transform(value, param1, param2) { 
    var result = value; 
    if(pram1) { 
     result = this.pipes[param1].transform(result); 
    } 
    if(pram2) { 
     result = this.pipes[param1].transform(result); 
    } 
    } 
} 

或將要使用的包裝管,如果管列表被用作陣列等

<div *ngFor="let hero of heroes | myPipe:['Cloud':'Location']" ></div> 
@Pipe({ 
    name: 'myPipe' 
}) 
export class MyPipe{ 
    locationPipe = new LocationPipe(); 
    cloudPipe = new CloudPipe(); 
    constructor() { 
    pipes = { 
     locationPipe: this.locationPipe, 
     cloudPipe: this.clouldPipe 
    }; 
    } 

    transform(value, params) { 
    var result = value; 
    for(var p in params) { 
     result = this.pipes[p].transform(result); 
    } 
    } 
} 
+0

感謝您的快速回答,th看起來很有希望。如果我可以使用它,我會稍後檢查它! –

+0

在你的例子中,LocationPipe是你導出的唯一管道嗎? (爲什麼LocationPipe是「自身」和cloudPipe的包裝?)在這種情況下,新的LocationPipe()是什麼?參考?是否暗示兩個管道(LocationPipe,CloudPipe)是從單獨的文件導入的(如我的示例中所示)並用於再次導出新的LocationPipe?對不起,但我沒有真正關注正在發生的事情。此外,我得到一個錯誤:屬性'管道'不存在類型'LocationPipe'在我的打字稿編譯器。我希望我不會錯過某些明顯的東西,你能否解釋一下你的例子中發生了什麼? –

+0

對不起,忘了重命名。我更新了我的答案。 'LocationPipe'和'CloudPipe'實際上不是用作管道,而是直接調用。他們也可以使用構造函數注入。 –