Tuesday, December 1, 2020

Using Angular Pipes in Component or Service Classes

In this tutorial we’ll see how to use Angular pipe in Component classes and Service classes in Angular.

Steps to use angular pipes in component classes (or Service)

If you want to use the pipe in more than one component class then configure it in app.module.ts class-

  1. Import the required Angular pipe and add it to the providers array.
  2. In the Component class inject the pipe and use it.

You can do these steps in Component class itself if specific Angular pipe is used in that class only.

Using Angular pipes in component class example

We’ll create a simple reactive form with fields to enter date and amount. Date has to be transformed using the DatePipe and amount using the CurrencyPipe in Component. For DatePipe configuration is done in App module where as for CurrencyPipe it is done in the Component class itself.

App Module (app.module.ts)

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { ReactiveFormsModule } from '@angular/forms';
import { DatePipe } from '@angular/common';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    AppRoutingModule
  ],
  providers: [DatePipe],
  bootstrap: [AppComponent]
})
export class AppModule { }

App Component (app.component.ts)

import { CurrencyPipe, DatePipe } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html', 
  providers: [CurrencyPipe]
})
export class AppComponent implements OnInit{
  membershipForm : FormGroup;
  constructor(private datePipe: DatePipe, private currencyPipe: CurrencyPipe){ }
  ngOnInit() {
    this.membershipForm = new FormGroup({
      mdate: new FormControl(this.datePipe.transform(Date.now(), 'yyyy-MM-dd')),
      amount: new FormControl(null)
    });
  }

  onSubmit(){
    console.log("Date-" + this.membershipForm.value.mdate);
    console.log("Currency-" + this.currencyPipe.transform(this.membershipForm.value.amount, 'USD'));
  }
}

In the Component class you can notice that-

  1. Instance of both DatePipe and CurrencyPipe is created in the Constructor which is injected by the Angular.
  2. For CurrencyPipe configuration is done in the Component class itself by adding it to the providers array with in the component.
  3. A reactive form named membershipForm is created with two fields ‘mdate’ and ‘amount’. Date field is pre-filled with the current date. Date is transformed to have the value in 'yyyy-MM-dd' format. Angular 6 onward you can also use formatDate(Date.now(), 'yyyy-MM-dd', ,this.locale). You will have to inject the required Locale if using formatDate() method.
  4. In the onSubmit() values of mdate and amount fields are logged to console which should be trasnformed as per the given format.
  5. Amount is transformed to have $ as currency.

Template (app.component.html)

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8">
      <h1>Membership Form</h1>
      <form [formGroup]="membershipForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
          <label for="mdate">Date</label>
          <input type="date" class="form-control" id="mdate"
          formControlName="mdate">                              
        </div>
        <div class="form-group">
          <label for="amount">Amount</label>
          <input type="number" class="form-control" id="amount"
          formControlName="amount">                        
        </div>
        <button type="submit" class="btn btn-success">Submit</button>
      </form> 
    </div>
  </div>
</div>
Angular pipe in component

That's all for this topic Using Angular Pipes in Component or Service Classes. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Custom Pipe in Angular With Example
  2. Pure and Impure Pipes in Angular
  3. Async Pipe in Angular With Examples
  4. Custom Async Validator in Angular Reactive Form
  5. Custom Async Validator in Angular Template-Driven Form

You may also like-

  1. What is Client Side Routing in Angular
  2. Creating New Component in Angular
  3. Angular HttpClient + Spring Boot REST API CRUD Backend Service
  4. Angular Cross Component Communication Using Subject Observable
  5. isAlive() And join() Methods in Java Multi-Threading
  6. ListIterator in Java
  7. Reading File in Java Using Scanner
  8. Python Exception Handling - try,except,finally

No comments:

Post a Comment