The problem is as follows: current time changes constantly, each mome
First of all you don't need to call ChangeDetectorRef.detectChanges()
inside your interval, because angular is using Zone.js
which monkey patches the browsers setInteral
method with its own. Therefore angular is well aware of the changes happening during an interval.
You should set the time inside your interval like this:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `{{ now }}`
})
export class AppComponent {
public now: Date = new Date();
constructor() {
setInterval(() => {
this.now = new Date();
}, 1);
}
}
But you shouldn't update the time on such a high rate, because it would lead to poor perfomance, because everytime the date updates angular performs a changedetection on the component tree.
If you want to update the DOM at a very high rate, you should use runOutsideAngular
from NgZone
and update the DOM manually using the Renderer2
.
For example:
@Component({
selector: 'my-counter',
template: ''
})
class CounterComponent implements OnChange {
public count: number = 0;
@ViewChild('counter')
public myCounter: ElementRef;
constructor(private zone: NgZone, private renderer: Renderer2) {
this.zone.runOutsideAngular(() => {
setInterval(() => {
this.renderer.setProperty(this.myCounter.nativeElement, 'textContent', ++this.count);
}, 1);
});
}
}