4

サーバーからデータを注文するための 3 つのカスタム パイプ (ASC、DESC、および既定) を作成しました。これらは完全に機能します。ユーザーの操作に応じて、この 3 つのパイプをアクティブにするかどうかを指定します。

問題は、たとえば変数を使用してカスタム パイプを変更することは可能かということです。

これは私のコードです...

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

1 に答える 1

4

異なるパイプを動的に割り当てる方法はありません。パラメータに応じて異なる動作をするパイプを作成できます

@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'

于 2016-10-12T16:37:00.367 に答える