Angular 2: Set and remove custom pipes?

我与影子孤独终老i 提交于 2019-12-23 12:17:18

问题


I've created three custom pipe to order data from server (ASC, DESC and Default), they work perfectly, I want that this three pipes active or not depending of the interaction of the user.

The question is, It's posible change the custom pipe with a variable for example?.

This is my code...

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

回答1:


There is no way to assign different pipes dynamically. You can create a pipe that behaves differently depending on a parameter

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

Where the pipe can be used like

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

while here pipe is a reference to an actual instance of the pipe class, not a string. You can inject pipes to your component like

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

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

You can also inject the pipes to the 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);
    }
  }
}

and then use it with a pipe name

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

Where pipe is 'pipe1' or 'pipe2'



来源:https://stackoverflow.com/questions/40003649/angular-2-set-and-remove-custom-pipes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!