AngularTechnology

Using Pipes in TypeScript (Angular)

angular typescript pipe

While it’s quite easy to use a pipe in Angular HTML code. In the following case, we are using a translate pipe.

<h2>{{ 'Hello' | translate }}</h2>

But using the same in TypeScript comes with some additional code setup.
The setup can be divided into two distinct ways.
1. Pipe without any Dependency
This method is the simplest one. We can just create an instance of the Pipe, and call it’s transform property with the text to transform as parameter.

@Pipe({
    name: 'custompipe',
    pure: false
})
export class MyCustomPipe implements PipeTransform {
    constructor() {}

    transform(key: string) {
        return keyTransformed;
    }
}
-------------------------------------
@Component({ ... })
export class MyComponent {
    customPipe: MyCustomPipe = new MyCustomPipe();
    
    constructor() { }

    getTranslatedText(text) {
        return this.customPipe.transform(text);
    }
}

2. Pipe with Dependency injected into constructor
This requires to pass the instance of any service that needs to be passed to the Pipe

@Pipe({
    name: 'translate',
    pure: false
})
export class TranslatePipe implements PipeTransform {
    constructor(private translateService: TranslateService) {}

    transform(key: string) {
        return this.translateService.translate(key);
    }
}
------------------------
@Component({ ... })
export class MyComponent {
    customPipe: TranslatePipe;
    
    constructor(private _translateService: TranslateService) {
        // Initialize the Pipe with Dependency Injection.
        this.customPipe = new TranslatePipe(this._translateService);
    }

    getTranslatedText(text) {
        return this.customPipe.transform(text);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *