【问题标题】:[Angular]Programatic Pipe creation?[Angular]程序化管道创建?
【发布时间】:2020-03-05 11:30:58
【问题描述】:

我想创建自定义动态 angular(7.2.2) 管道。

例如:用户将编写类似下面的代码(用户可能也必须传递参数,但仍未找到发送参数的理想方式。)

var myPage={};
   myPage.registerPipe('myPipe', function myPipeFun(parama1, param2){});

现在我想做的是上面的 sn-p 应该转换成角管。

例如:我应该能够生成下面的代码,是否可以生成类似于下面的管道代码角度?

import {
    Injector,
    Pipe,
    PipeTransform
} from '@angular/core';


@Pipe({
  name: 'myPipe'
})
export class myPipe implements PipeTransform {

    public constructor(private injector: Injector) {
    }

    transform(value: any, pipeToken: any, pipeArgs: any[]): any {
       myPipeFun(value, ...);
    }
}

【问题讨论】:

    标签: angular angular-pipe


    【解决方案1】:

    我认为这在 Angular 中是不可能的。

    相反,我建议创建一个通用Pipe

    第一种方式

    Pipe 获取回调函数作为第二个参数

    export class UniversalPipe implements PipeTransform {
    
        transform(value: any, callBackFun): string {
            console.log(value);
            return callBackFun();
        }
    }
    

    您可以将动态callback 函数从您的组件传递给这个通用Pipe

    <p>
      {{'Start editing to see some magic happen' | universalPipe: myFun}}
    </p>
    

    第二种方式

    您可以在 Pipe 本身中定义所有函数,并将类型而不是 callback 函数传递给 Universal Pipe 并执行相应的函数

    这里是StackBlitz 项目

    【讨论】:

      猜你喜欢
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 2011-01-25
      相关资源
      最近更新 更多