display digital clock in angular

Solutions on MaxInterview for display digital clock in angular by the best coders in the world

showing results for - "display digital clock in angular"
Amel
11 Mar 2020
1// in ts file
2
3import { Component, OnInit } from '@angular/core';
4import { Subscription, timer } from 'rxjs';
5import { map, share } from "rxjs/operators";
6import { OnDestroy } from '@angular/core';
7
8
9@Component({
10  selector: 'app-clock',
11  templateUrl: './clock.component.html',
12  styleUrls: ['./clock.component.scss']
13})
14export class ClockComponent implements OnInit, OnDestroy {
15
16  date: Date = new Date();
17
18  constructor() {
19  }
20
21  time = new Date();
22  rxTime = new Date();
23  intervalId;
24  subscription: Subscription;
25
26  ngOnInit() {
27    // Using Basic Interval
28    this.intervalId = setInterval(() => {
29      this.time = new Date();
30    }, 1000);
31
32    // Using RxJS Timer
33    this.subscription = timer(0, 1000)
34      .pipe(
35        map(() => new Date()),
36        share()
37      )
38      .subscribe(time => {
39        this.rxTime = time;
40      });
41  }
42
43  ngOnDestroy() {
44    clearInterval(this.intervalId);
45    if (this.subscription) {
46      this.subscription.unsubscribe();
47    }
48  }
49
50}
51
52// in html
53 Simple Clock:
54 <div>{{ time | date: 'hh:mm:ss a' }}</div>
55 RxJS Clock:
56 <div>{{ rxTime | date: 'hh:mm:ss a' }}</div>
57