Using Custom Pipes inside an Angular Component Class

Using Custom Pipes inside an Angular Component Class

In this tutorial, we’re going to learn to use Angular Pipes inside a component class. In one of my previous tutorials, we’ve created a custom pipe that accepts a number and returns its square. For this tutorial we’re going to inject that pipe inside a component

Before you can use your pipe inside a component class you need to add it to providers array of your module.

providers: [SquarePipe,...]

Next thing you need to do is you need to inject the pipe as service in the constructor of your component class.

// ...
import { SquarePipe } from './square.pipe';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
export class AppComponent {

    private square: SquarePipe
  ) { }

  // ...

And, To use this pipe you need to simply utilise the transform method on the instance of pipe object injected in the class.

getSquare(val): void {
  this.squareVal = this.square.transform(val);
  // ...

And that’s it. In case, you’ve any query or feedback feel free to drop a comment.

One thought on “Using Custom Pipes inside an Angular Component Class”

Leave a Reply

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