Angular 2: Set and remove custom pipes?

2019-06-27 00:10发布

问题:

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'