Dynamic pipe in Angular 2

后端 未结 6 978
失恋的感觉
失恋的感觉 2020-12-01 12:35

I\'m trying to create a component where you can pass which pipe that should be used for a list inside the component. From what I could find by testing and looking around for

6条回答
  •  借酒劲吻你
    2020-12-01 13:26

    Building on @Balu answer this what I had to do to get it working with Angular 9

    import { Injector, Pipe, PipeTransform } from '@angular/core';
    import { PercentPipe, CurrencyPipe, DecimalPipe } from '@angular/common';
    
    @Pipe({
        name: 'dynamicPipe'
    })
    
    export class DynamicPipe implements PipeTransform {
    
        public constructor(private injector: Injector, private percentPipe: PercentPipe) {
        }
    
        transform(value: any, pipeToken: any, pipeArgs: any[]): any {
    
            const MAP = { 'currency': CurrencyPipe, 'decimal': DecimalPipe, 'percent': PercentPipe }
    
            if (pipeToken && MAP.hasOwnProperty(pipeToken)) {
                var pipeClass = MAP[pipeToken];
                var pipe = this.injector.get(pipeClass);
                if (Array.isArray(pipeArgs)) {
                    return pipe.transform(value, ...pipeArgs);
                } else {
                    return pipe.transform(value, pipeArgs);
                }
            }
            else {
                return value;
            }
        }
    }
    

提交回复
热议问题