user6123723 user6123723 - 3 months ago 10
TypeScript Question

How to use a pipe in two different Angular Modules

I have a pipe

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
.....
return keys;
}
}


I have two modules in which I need to use this. If I do something like this in both the modules, I get an error saying that "two modules declare KeysPipe"

Module1, Module2:

declarations: [KeysPipe],


I then tried exporting KeysPipe through it's own module so that I can import it in to the two modules in which I need to use it

@NgModule({
declarations: [ KeysPipe],
})
export class KeysPipeModule {
}


Now I'm importing the KeysPipeModule in the two modules I need to use KeysPipe

Module1, Module2:

imports: [KeysPipeModule],


But now I get a different template error saying that the pipe isn't found "The pipe 'keys' could not be found ("v *ngIf="docalc">"

Answer

You're on the right track the only thing your code is missing is the export in the KeysPipeModule. This is what it should look like:

@NgModule({
    declarations: [ KeysPipe],
    exports: [KeysPipe]
})
export class KeysPipeModule {}