user8476523
user8476523

Reputation:

Why do we use "PipeTransform" in custom pipes?

Here is my custom pipe:

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

@Pipe({
  name: 'dc'
})
export class DcPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    if (!value) return value;

    return value.replace(/\w\S*/g, function(txt) {
      return txt.charAt(0).toLowerCase() + txt.substr(1).toUpperCase();
    });
  }
}

What's the purpose of using implements PipeTransform in a class declaration?

From what I see is working even without this part.

Upvotes: 4

Views: 6820

Answers (2)

Dylan Wright
Dylan Wright

Reputation: 1212

Here is the API definition: https://angular.io/api/core/PipeTransform

Link to the code behind: https://github.com/angular/angular/blob/5.1.3/packages/core/src/change_detection/pipe_transform.ts#L1-L38

PipeTransform is a simple interface, it's describing what should be expected expectations of implementation, nothing more.

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191809

PipeTransform is an interface: https://angular.io/api/core/PipeTransform

Including it and using implements PipeTransform ensures that your class will implement the required transform method and conform to its interface (specifically requiring the first value parameter ... it doesn't do much else).

Conforming to the interface catches possible runtime errors (during transpile time) including but possibly not limited to:

  • Not implementing transform at all
  • Not returning a value from transform

This is similar to implements OnInit / ngOnInit. You don't have to implement it for the code to work, but it's a good practice.

Upvotes: 5

Related Questions