Build Temparature Convertor Application Using Angular and Bootstrap

Introduction

In this tutorial, I will show you how to build a Temperature converter application using Angular Custom Pipe. The Pipes are the best way to transform the appearance of elements in the template. There are built-in pipes like Date pipes, Currency pipes, and Number pipes, etc in Angular. But if these pipes can't fulfill the requirements, then we can build our own pipe in Angular is called Custom Pipe in Angular.

Note. Before going through this session, please visit my previous article related to Angular applications as mentioned below.

Angular Application

Step 1. Create a new pipe Under the folder src/app is called temp-convertor.pipe.ts

D:\EmployeeManagement\CallWebAPIAngular\src\app> ng generate pipe temp-convertor

Step 2. Add code in temp-convertor.pipe.ts

Here is the Temperature converter pipe, which converts temperature from Celsius to Fahrenheit and vice versa.

import {Pipe, PipeTransform} from '@angular/core';
 
@Pipe({
    name: 'tempConverter'
})
export class TempConverterPipe implements PipeTransform {
    transform(value: number, unit: string) {
        if(value && !isNaN(value)) {
            if (unit === 'C') {
                var temperature = (value - 32) /1.8 ;
                return temperature.toFixed(2);
            } else if (unit === 'F'){
                var temperature = (value * 1.8 ) + 32
                return temperature.toFixed(2);
            }
        }
        return;
    }
}

Code Description

import the Pipe & PipeTransform libraries from Angular. These libraries are part of the Angular Core.

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

Here I decorate TempConverterPipe class with @pipe decorator.

export class TempConverterPipe implements PipeTransform {

The @Pipe decorator tells Angular that the class is a pipe and the decorator expects us to provide a name to the pipe. We have given it as tempConverter. This is the name we must use in the template to make use of this pipe.

@Pipe({
    name: 'tempConverter'
})

The class called TempConverterPipe must implement the PipeTransform interface.

export class TempConverterPipe implements PipeTransform {
    transform(value: number, unit: string) {

The PipeTransform interface defines only one method transform. An interface that is implemented by pipes in order to perform a transformation. Angular invokes the transform method with the value of binding as the first argument and any parameters as the second argument in list form.

The interface definition is as follows.

export class TempConverterPipe implements PipeTransform {
    transform(value: number, unit: string) {

The first argument value is the value, that the pipe needs to transform. We can also include any number of arguments. The method must return the final transformed data.

The logic implementation of the transform method for the Temperature Converter is shown below.

transform(value: number, unit: string) {
        if(value && !isNaN(value)) {
            if (unit === 'C') {
                var temperature = (value - 32) /1.8 ;
                return temperature.toFixed(2);
            } else if (unit === 'F'){
                var temperature = (value * 1.8 ) + 32
                return temperature.toFixed(2);
            }
        }
        return;
    }

The first is Value and the second is the Unit. The unit expects either C (Convert to Celsius) or F ( convert to Fahrenheit). It converts the value received to either Celsius or Fahrenheit based on the Unit.

Step 3. Pipe Declaration in app.module.ts

To use our custom pipe, we need to tell our component, where to find it. This is used first by importing it and then including it in the declarations array of the AppModule or app.module.ts file. Also, we need to import FormsModule and include it in the imports array of the AppModule or app.module.ts file else we might get an issue called Can't bind to 'ngModel' since it isn't a known property of 'input'.

import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { OneComponent } from './one/one.component';
import { TwoComponent } from './two/two.component';
import { ThreeComponent } from './three/three.component';
import { TempConverterPipe } from './temp-convertor.pipe';
 
@NgModule({
  declarations: [
    AppComponent,OneComponent,TwoComponent,ThreeComponent, TempConverterPipe
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [Title],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4. Add code in app.component.html

<div class="card bg-info text-white" style="width: 76rem;">
  <div class="card-header">{{title}}</div>
  <div class="card-body">
    <div>
      <input type="text" class="form-control" [(ngModel)]="Fahrenheit" placeholder="Enter Fahrenheit"/> 
      <label class="col-sm-4 col-form-label">Fahrenheit to Celsius : {{Fahrenheit | tempConverter:'C'}} </label>
    </div>
    <div>
      <input type="text" class="form-control" [(ngModel)]="celcius"  placeholder="Enter Celsius"/> 
      <label class="col-sm-4 col-form-label">Celsius to Fahrenheit : {{celcius | tempConverter:'F'}} </label>
    </div>
  </div>
</div>

Here the custom pipes are used in the same as the Angular built-in pipes are used.

Code Description

We use our pipe as follows.

{{celcius | tempConverter:'F'}}

celcius is sent to the tempConverter as the first argument value. We use the | to indicate that the tempConverter is a pipe to angular. The F after the colon is the first argument. You can pass more than one argument to the pipe by separating each argument by a: colon.

{{Fahrenheit | tempConverter:'C'}}

Fahrenheit is sent to the tempConverter as the first argument value. We use the | to indicate that the tempConverter is a pipe to angular. The C after the colon is the first argument. You can pass more than one argument to the pipe by separating each argument by a: colon.

Here Fahrenheit is the value parameter and C is the unit parameter of the transform() method. tempConverter is the name of the pipe mentioned in @Pipe decorator. These are mapped to the temp-convertor.pipe.ts file.

transform(value: number, unit: string) {

Here [(ngModel)]="Fahrenheit" should be mapped to Fahrenheit which is sent to the tempConverter as the first argument value.

<input type="text" class="form-control" [(ngModel)]="Fahrenheit" placeholder="Enter Fahrenheit"/> 

Step 5. Add code in app.component.ts

import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title: string = 'Angular Temparature Convertor Application' ;
  celcius!: number;
  Fahrenheit!: number;  
 
  constructor(private titleService:Title) {
  }
 
  ngOnInit() {
    this.titleService.setTitle(this.title);
  }
}

Code Description

Here we declare 3 properties as shown below.

export class AppComponent {
  title: string = 'Angular Temparature Convertor Application' ;
  celcius!: number;
  Fahrenheit!: number; 

The Celsius and Fahrenheit properties are used to map for data binding in app.component.html. There are 2 ways of data binding i.e. Interpolation and Two-way Binding are used in app.component.html.

Step 6. Add Bootstrap CDN in index.html to make a responsive design

It is used for styling the application.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Title Service Example</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Steps to Build Custom Pipes in Angular

  1. To create a custom pipe, first, we need to create a pipe class.
  2. The pipe class must implement the PipeTransform interface.
  3. We also decorate it with @pipe decorator.
  4. Give a name to the pipe under the name metadata of the @pipe decorator.
  5. Finally, we create the transform method, which transforms the given value to the desired output.

These steps In Detail

  1. Create a pipe class
  2. Decorate the class with the @pipe decorator.
  3. Give a name to the pipe in the name metadata of the @pipe decorator. We will use this name in the template.
  4. The pipe class must implement the PipeTransform interface. The interfaces contain only one method transform.
  5. The first parameter of the transform method is the value to be transferred. The transform method must transform the value and return the result. You can add any number of additional arguments to the transform method.
  6. Declare the pipe class in the Angular Module (app.module.ts)
  7. Use the custom pipe just as you use other pipes.

Output

Angular temperature

Let's check how it works.

Application working

Summary

In this write-up, we have learned the details below.

  • Know about Pipe in Angular
  • How to use Pipe in Angular
  • Steps to build Temperature Convertor application using Angular

Thank You & Stay Tuned For More


Similar Articles