2016-10-12 4 views
4

サーバー(ASC、DESC、およびデフォルト)からデータを注文する3つのカスタムパイプを作成しましたが、これらは完全に機能します。この3つのパイプがアクティブかどうかは、ユーザーの操作に依存します。角2:カスタムパイプを設定して削除しますか?

質問は、変数を使用してカスタムパイプを変更することが可能ですか?

これは、動的に別のパイプを割り当てる方法はありません...

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

答えて

2

私のコードです。パイプクラスの実際のインスタンスへの参照である、ここでpipeながら あなたは、異なったパイプが

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

のように使用することができるパラメータ

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

に応じて振る舞うのパイプを作成することができません文字列。あなたは

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); 
    } 
    } 
} 

にパイプを注入し、その後、パイプ名でそれを使用することができますpipeがある

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

'pipe1'または'pipe2'

+0

答えをありがとう!パイプは完全に動作しています:D – Danny908

+0

嬉しいです。フィードバックをお寄せいただきありがとうございます :) –

関連する問題