Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display time/clock in angular

Tags:

angular

rxjs

I am using below method to display time in my app?

constructor(private datePipe: DatePipe) {}
ngOnInit() {
    this.getTime();
    this.date = this.datePipe.transform(new Date(), "dd/MM/yyyy");
  }
 getTime() {
    setInterval(() => {
      this.time = this.datePipe.transform(new Date(), "HH:mm:ss");
      this.getTime();
    }, 1000);
  }

this code is working fine but after some time application getting crashed. is there any alternative way to display time in angular4/5/6?

like image 656
Santhosh Avatar asked Jan 21 '19 11:01

Santhosh


2 Answers

Inside component.ts

  time = new Date();
  rxTime = new Date();
  intervalId;
  subscription: Subscription;

  ngOnInit() {
    // Using Basic Interval
    this.intervalId = setInterval(() => {
      this.time = new Date();
    }, 1000);

    // Using RxJS Timer
    this.subscription = timer(0, 1000)
      .pipe(
        map(() => new Date()),
        share()
      )
      .subscribe(time => {
        this.rxTime = time;
      });
  }

  ngOnDestroy() {
    clearInterval(this.intervalId);
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }

Inside component.html

Simple Clock:
<div>{{ time | date: 'hh:mm:ss a' }}</div>
RxJS Clock:
<div>{{ rxTime | date: 'hh:mm:ss a' }}</div>

Working demo

like image 58
Niral Munjariya Avatar answered Sep 22 '22 09:09

Niral Munjariya


Alternative using an observable and "onPush" change detection

import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Observable, timer } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
    selector: 'time',
    template: "{{ $time | async | date: 'hh:mm:ss a' }}",
    styleUrls: ['./time.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TimeComponent {
    public $time: Observable<Date> = timer(0, 1000).pipe(map(() => new Date()));
}
like image 28
Flavien Volken Avatar answered Sep 22 '22 09:09

Flavien Volken