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
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.