How to useDependency Injection in Angular
You can create a service that holds the string value, inject it into the pipe’s constructor, and then use that value within the pipe’s transformation logic.
Step 1: Create a new Service
ng generate service value-holding
Code Example:
<!-- app.component.html -->
<h1>Reverse Pipe Demo</h1>
<p>Original: {{ 'Hello, World!' }}</p>
<p>Reversed: {{ 'Hello, World!' | reverse}}</p>
//value-holding.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ValueHoldingService {
constructor() { }
suffix = ' Suffix';
}
//reverse.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { SuffixService } from './suffix.service';
@Pipe({
name: 'reverse',
pure: true,
standalone: true
})
export class ReversePipe implements PipeTransform {
constructor(private suffixService: SuffixService) { }
transform(value: string): string {
return `${value.split('')
.reverse().join('')}${this.suffixService.suffix}`;
}
}
In this approach, we create a SuffixService that holds the string value ‘ Suffix’. We then inject this service into the ReversePipe constructor and use the suffix property within the transform method.
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.