Display time/clock in angular

Alternatively, you can use observables:

private _time$: Observable<Date> = timer(0, 1000).pipe(
  map(tick => new Date()),
  shareReplay(1)
);

get time() {
  return this._time$;
}

And in your html:

{{ time | async | date: 'hh:mm:ss a' }}

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


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()));
}

Tags:

Angular

Rxjs