How do you register custom pipes in Angular 17?

2.5k views Asked by At

I just created a custom Pipe and normally I would register it in app.module.ts, but In Angular 17 we dont have that file. How do we register now? TIA

I was thinking of importing into the imports array as you would with other modules, but that didnt work. I tried checking the angular.dev site but for some reason it wont load on my laptop. Any help is appreciated.

2

There are 2 answers

2
Winthorpe On

For a standalone component, register the custom pipe in the imports array in .component.ts like this:

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CustomPipe } from '../custom.pipe';

@Component({
  selector: 'app-test',
  standalone: true,
  imports: [CommonModule, CustomPipe], <-- register pipe here
  templateUrl: './test.component.html',
  styleUrl: './test.component.scss'
})
export class TestComponent { }

Then use the pipe in the template as usual:

<p>{{ 'test' | customPipe }}</p>

The example code snippets above, assumes the custom pipe is like this:

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

@Pipe({
  name: 'customPipe',
  standalone: true
})
export class CustomPipe implements PipeTransform {

  transform(value: string): string[] {
    return value.split('');
  }
}

Also see the official Angular guide: Using a pipe in a template.

0
amphetamachine On

You can do it a couple different ways:

  1. Load it in the component you use it in:
// foo.component.ts
import { Component } from '@angular/core';
import { CustomPipe } from '../custom.pipe';

@Component({
  imports: [CustomPipe], <-- register pipe here
  selector: ...,
  styleUrl: ...,
  templateUrl: ...,
})
export class FooComponent { }
  1. Load it at the module level:

If your project has multiple modules, and only one of those modules has components in that make use of the pipe, you should just put it in that module:

// mypages.module.ts
import { CustomPipe } from '../custom.pipe';

@NgModule({
    imports: [...]
    declarations: [
        // Components
        FooComponent,

        // Pipes
        CustomPipe,
    ],
})
export class MyPagesModule { }
  1. Same thing as #2, but put it app.module.ts instead so it's available in every component.