Menu Close

How to use pipes in Component Class

In this article we will learn about How to use pipes in Component Class. Usage of pipes in component class is a little bit different. First, we need to import pipe from Angular common library and add it to providers array of the component and then we need to inject in the constructor of the class. Please read my previous article Chaining Pipes in Angular.

Every pipe has transform method which takes inputs and the result will be applied to the title here.

  • Imported the UpperCasePipe from angular common library.
  • Added the pipe into providers.
  • Inject the pipes into constructor.
  • Then use it to transform to uppercase.
import { UpperCasePipe } from '@angular/common';
import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ UpperCasePipe ]
})
export class AppComponent {

  constructor(private upperCasePipe: UpperCasePipe) {}
  
  title = this.upperCasePipe.transform('angularpipes use in component class');

}
<p> {{ title }} </p>

The output is printed in uppercase that we made on typescript file.

How to pass parameters to pipes in Component Class

Letā€™s see how we can pass parameters to pipe in component class. If we can look at the below file that we are passing as arguments to the transform method

import { DecimalPipe, UpperCasePipe } from '@angular/common';
import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ DecimalPipe ]
})
export class AppComponent {

  constructor(private decimalPipe: DecimalPipe) {}

  number = this.decimalPipe.transform('3.3666', '2.1-2', 'en');

}
<p>{{number}}</p>

Conclusion

In this article we will learnt about How to use pipes in Component Class. Usage of pipes in component class is a little bit different. First, we need to import pipe from Angular common library and add it to providers array of the component and then we need to inject in the constructor of the class.

Leave behind your valuable queries and suggestions in the comment section below. Also, if you think this article helps you, do not forget to share this with your developer community. Happy Coding šŸ™‚

Related Articles

Jayant Tripathy
Coder, Blogger, YouTuber

A passionate developer keep focus on learning and working on new technology.

Leave a Reply

Your email address will not be published.