Dynamic pipe in Angular 2

后端 未结 6 1000
失恋的感觉
失恋的感觉 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:17

    I handled this by sending the pipe provider to the component and it runs the transform method. And It works with Angular 9. I hope it helps someone! Demo: https://stackblitz.com/edit/angular-kdqc5e

    pipe-injector.component.ts:

    import { Component, OnInit, Input, PipeTransform } from '@angular/core';
        @Component({
          selector: 'pipe-injector',
          template: `
            Should inject my pipe provider 
            {{ getText() }}
            `,
          providers: []
        })
    
    
        export class PipeInjectorComponent {
          @Input() pipeProvider: PipeTransform;
          @Input() pipeArgs: Array;
          @Input() textToFormat: string;
    
          getText() {
            return this.pipeProvider.transform(this.textToFormat, ...this.pipeArgs);
          }
        }
    

    app-component.ts:

    import { Component, OnInit } from '@angular/core';
    import { DatePipe } from '@angular/common';
    
    @Component({
      selector: 'app-root',
      template: `
         
        
        `,
      providers: []
    })
    
    export class AppComponent implements OnInit {
      pipeArgs = ['dd/MM/yyyy'];
      constructor(public pipeProvider: DatePipe) {}
    }
    

    app.module.ts:

    import { DatePipe } from '@angular/common';
    import { PipeInjectorComponent } from './pipe-injector.component';
    
    @NgModule({
      declarations: [
    
        PipeInjectorComponent,
      ],
      imports: [
      ],
      providers: [
        DatePipe,
        ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

提交回复
热议问题