2

In Angular 18, is it possible to have a custom standalone pipe that uses another pipe?

Here is what I am trying to do:

import { inject, Pipe, PipeTransform } from '@angular/core';
import { CurrencyPipe } from '@angular/common';

@Pipe({
    name: 'currencyZeroBlank',
    standalone: true,
})
export class CurrencyZeroBlankPipe implements PipeTransform {
    private readonly currencyPipe = inject(CurrencyPipe);

    public transform(value: number | undefined): string {
        if (value === null || value === 0) {
            return '';
        }
        return this.currencyPipe.transform(value, 'EUR')!;
    }
}

But I get

NullInjectorError: No provider for _CurrencyPipe!

For a standalone component, this would be only a matter of

imports: [CommonModule],

but for a pipe this does not work. Can it be done, or do I need to add a module and declare it?

2
  • Yeah looking through the docs I'm not seeing an immediate way around this. I'd have a crack adding a module. If it helps, it looks like this question dealt with a similar issue (not standalone though) Commented Dec 17, 2024 at 15:16
  • 1
    Just flagging as well, that you might be able to achieve what you're after by chaining pipes (warning: old docs) as opposed to injecting one pipe into another Commented Dec 17, 2024 at 15:18

1 Answer 1

1

It is not recommended to compose pipes in Angular. Pipes shouldn't be injected. Instead, you should chain them. This would probably suit your needs better:

<p>{{ myNumber | currencyZeroBlank | currencyPipe : 'EUR' }}</p>

If you really want the whole logic to be in a single pipe and to avoid chaining pipes, I would suggest having a simple typescript/javascript file that contains the function used by your currencyPipe. Any other pipe, or components and services, will then be able to use the currencyPipe's parsing function directly. Pipes should be kept for the template.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.