Angular 2:设置和删除自定义管道?

Angular 2: Set and remove custom pipes?

我已经创建了三个自定义管道来从服务器(ASC、DESC 和默认)订购数据,它们工作得很好,我希望这三个管道是否处于活动状态,具体取决于用户的交互。

问题是,是否可以使用变量更改自定义管道?

这是我的代码...

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

无法动态分配不同的管道。 您可以根据参数创建行为不同的管道

@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 的实际实例的引用,而不是字符串。 您可以像

一样将管道注入组件
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'