Angular Dynamic Pipe

134 views Asked by At

I am trying to build the dynamic pipe and though I have included the pipes in the app module provider, it is throwing the NullInjector error.

I would suggest to open the Console window inside the Developer options to see the error.

I have also attached the below link for the demo.

In a real scenario, the pipe value will be coming from the server so I am in need of a dynamic pipe.

https://stackblitz.com/edit/angular-lcidq5-q1a3hv?file=src%2Fapp%2Ftest%2Ftest.component.html

3

There are 3 answers

1
Cuzy On BEST ANSWER

A string does not work as a valid token for the inject method.

I suggest creating an object that stores the types of your pipes:

import { Injector, Pipe, PipeTransform } from '@angular/core';
import { CustomPipe } from './custom.pipe';

const pipes = {
  fullform: CustomPipe,
};

@Pipe({
  name: 'dynamic',
})
export class DynamicPipe implements PipeTransform {
  public constructor(private injector: Injector) {}

  transform(value: any, pipeToken: any, pipeArgs: any[]): any {
    if (!pipeToken) {
      return value;
    } else {
      let pipe = this.injector.get<any>(pipes[pipeToken]);
      return pipe.transform(value, ...pipeArgs);
    }
  }
}

This way, you will have to add the pipes to this object for it to work, but you can pass the strings you get from your API and convert them to their respective injector token.

0
DEV On

You just to define a provider on the module

enter image description here

@NgModule({
  bootstrap: [AppComponent],
  declarations: [AppComponent, TestComponent, DynamicPipe, CustomPipe],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    TooltipsModule,
    DateInputsModule,
    ButtonsModule,
  ],
  providers: [
    CustomPipe,
    DynamicPipe,
    { provide: 'fullform', useClass: CustomPipe },
  ],
})
export class AppModule {}
0
Jameson Saunders On

To inject the provider by string, you need to map the token to the pipe in the app.module.ts:

providers: [{ provide: 'fullform', useValue: CustomPipe }],

Then, in your dynamic pipe, you need to instantiate the pipe:

let Pipe = this.injector.get<any>(pipeToken);
let pipe = new Pipe();
return pipe.transform(value, ...pipeArgs);

https://stackblitz.com/edit/angular-lcidq5-w94gsj?file=src%2Fapp%2Fdynamic.pipe.ts