Here, we will develop the angular application for setting the timer using a @pipe. Pipe are used to transform the data, but we can use it in multiple ways.
Step1: Create a new project.
ng new timer-pipe
Step2: Install node_modules
npm install
Step3: Add Component
ng g c set-timer
Step4: In set-timer.component.ts
import { Component, OnInit,OnDestroy } from '@angular/core'; import { timer, Subscription } from "rxjs"; import { Pipe, PipeTransform } from "@angular/core"; @Component({ selector: 'app-set-timer', templateUrl: './set-timer.component.html', styleUrls: ['./set-timer.component.css'] }) export class SetTimerComponent implements OnInit, OnDestroy { countDown: Subscription|any; counter:string|any; time:string|any; tick = 1500; ngOnInit() { } ngOnDestroy() { this.countDown = null; } startTimer(){ this.counter=this.time; this.countDown = timer(0, this.tick).subscribe(() => --this.counter); this.time=""; } }
Step5: Add pipe
@Pipe({ name: "formatTime" }) export class FormatTimePipe implements PipeTransform { transform(value: number): string { const hours: number = Math.floor(value / 3600); const minutes: number = Math.floor((value % 3600) / 60); return ( ("00" + hours).slice(-2) + ":" + ("00" + minutes).slice(-2) + ":" + ("00" + Math.floor(value - minutes * 60)).slice(-2) ); } }
Step6: In set-timer.component.html
<div class="container"> <div> <h3>Write Only Seconds</h3> <input type="text" [(ngModel)]="time"> <button (click)="startTimer()">Start</button> </div> <div *ngIf="counter"> <label>Timer:</label> {{counter|formatTime}} </div> </div>
Step7: Add pipe in app.module.ts
import{FormatTimePipe} from './components/set-timer/set-timer.component' declarations: [ FormatTimePipe ],
Step8: Now, Run the Application
npm start