Lycodo
Lycodo

Reputation: 43

Angular Standalone Pipe with Dependencies

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?

Upvotes: 2

Views: 212

Answers (1)

Olivier
Olivier

Reputation: 56

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.

Upvotes: 1

Related Questions