Reputation: 101
I'm developing an app using Angular 8 (angular.io) and notice that the press/mousedown/touchstart events have a delay before they are fired, or at least before any response is seen in the view. Is there way to lower this delay or remove it? It happens on both my laptop and a touch screen panel so I know it's not device specific.
Upvotes: 1
Views: 294
Reputation: 11
Do you use OnPush change detection strategy for your component?
If yes, then I expect that your data changes asynchronously. That means change detection is not triggered when you data is ready - hence the application doesn't re-draw the component. Even you data is actually changed, you won't see changes on your screen before next change detection is triggered.
In that case you have several options to do:
1) Use Observable
(Subject
, BehaviorSubject
or plain Observable
) with async
pipe in your HTML instead of data you use.
app.component.ts:
import { BehaviorSubject } from "rxjs";
class AppComponent {
counter$ = new BehaviorSubject(0);
onClick(): void {
setTimeout(() => {
this.counter$.next(this.counter$.getValue() += 1);
});
}
}
app.component.html
<div>You clicked {{ counter$ | async }} times</div>
2) Inject ChangeDetectorRef into the constructor of your component and trigger change detection manually.
app.component.ts:
import { ChangeDetectorRef } from "@angular/core";
class AppComponent {
counter = 0;
constructor(private cdr: ChangeDetectorRef) {
}
onClick(): void {
setTimeout(() => {
this.counter += 1;
this.cdr.detectChanges();
});
}
}
Here you can find an explanation of ChangeDetectionStrategy.OnPush: https://blog.angular-university.io/onpush-change-detection-how-it-works/
Upvotes: 1