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?
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()));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With