【问题标题】:Angular 2: Set and remove custom pipes?Angular 2:设置和删除自定义管道?
【发布时间】:2016-10-12 16:24:37
【问题描述】:

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

问题是,例如可以用变量更改自定义管道吗?

这是我的代码...

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

【问题讨论】:

    标签: angular pipe custom-pipeline-component


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答!!管道工作正常:D
    • 很高兴听到。感谢您的反馈:)
    猜你喜欢
    • 1970-01-01
    • 2016-10-02
    • 2017-10-11
    • 2023-04-03
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多