I am currently working on developing a clock component that displays the current time in real-time.
Issue: The initial time is correctly displayed when the page loads (HH:mm A), but the clock does not update dynamically.
clock.component.ts :
import {
ChangeDetectionStrategy,
Component,
OnInit
} from "@angular/core";
import { Observable, interval } from "rxjs";
import { map, distinctUntilChanged } from "rxjs/operators";
import * as moment from "moment";
@Component({
selector: "app-clock",
templateUrl: "./clock.component.html",
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ClockComponent implements OnInit {
pageLoaded: moment.Moment;
time: Observable<string>;
constructor() {}
ngOnInit() {
this.pageLoaded = moment(new Date());
this.time = interval(1000).pipe(
map(() => this.pageLoaded.format("HH:mm A")),
distinctUntilChanged()
);
}
}
clock.component.html :
<div>{{ time | async }}</div>