How to usethe NgModule decorator in Angular
In this approach, you can pass the string value to the pipe’s constructor using Angular’s dependency injection system and the @Inject decorator by creating a value in the providers array of the NgModule.
Step 1: Generate a new Angular project
ng new string-pipe-demo
Step 2: Generate a new pipe
ng generate pipe reverse
Folder Structure:
Code Example:
//reverse.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse',
pure: true
})
export class ReversePipe implements PipeTransform {
constructor(private suffix: string) { }
transform(value: string): string {
return `${value.split('')
.reverse().join('')}${this.suffix}`;
}
}
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ReversePipe } from './reverse.pipe';
@NgModule({
declarations: [
AppComponent,
ReversePipe
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In this example, we’re creating a pipe called ReversePipe that takes a string as input, reverses it, and appends a suffix to the end.
Output:
How to pass a string to a custom pipes constructor – Angular 16
In Angular, custom pipes are a powerful tool for transforming data in templates. While simple pipes perform basic transformations, there are cases where you may need to pass parameters to customize the behavior of a pipe. Fortunately, Angular provides mechanisms for passing parameters to custom pipes, allowing you to create more versatile and reusable transformations. In this article, we’ll learn how to pass parameters to custom pipes in Angular.