2016-10-12 37 views
4

我已經創建了三個自定義管道來從服務器(ASC,DESC和默認)訂購數據,他們工作完美,我希望這三個管道活動或不依賴於用戶的交互活動。Angular 2:設置和刪除自定義管道?

問題是,它可能改變自定義管道的變量,例如?

這是我的代碼...

<label *ngFor="let user of users | {{pipeOrderType}}:'name'">{{user.id}}{{user.name}}, </label> 

回答

2

有沒有辦法來動態分配不同管道。 您可以創建行爲有所取決於參數

@Pipe({ 
    name: 'dynamicPipe' 
}) 
class DynamicPipe implements PipeTransform { 
    transform(value, pipe) { 
    if(!value || !pipe) { 
     return null; 
    } 
    return pipe.transform(value); 
    } 
} 

凡管可以像

<label *ngFor="let user of users | dynamicPipe:pipe">{{user.id}}{{user.name}}, </label> 

中使用的管道,而這裏pipe是管類的實際實例的引用,不一個字符串。 您可以像

class MyComponent { 
    constructor(private pipe1:Pipe1, private pipe2:Pipe2) {} 

    clickHandler() { 
    if(xxx) { 
     this.pipe = this.pipe1; 
    } else { 
     this.pipe = this.pipe2 
    } 
    } 
} 

注入管道的組件,您也可以注入管道輸送到dynamicPipe

@Pipe({ 
    name: 'dynamicPipe' 
}) 
class DynamicPipe implements PipeTransform { 
    constructor(private pipe1:Pipe1, private pipe2:Pipe2) {} 

    transform(value, pipe) { 
    if(!value || !pipe) { 
     return null; 
    } 
    if(pipe == 'pipe1') { 
     return pipe1.transform(value); 
    } 
    if(pipe == 'pipe2') { 
     return pipe2.transform(value); 
    } 
    } 
} 

,然後用管道名稱使用

<label *ngFor="let user of users | dynamicPipe:pipe">{{user.id}}{{user.name}}, </label> 

哪裏pipe'pipe1''pipe2'

+0

感謝您的回答!管道工作正常:D – Danny908

+0

很高興聽到。感謝您的反饋 :) –

相關問題