我正在使用Angular 8(angular.io)开发应用程序,请注意,按下/鼠标按下/触摸启动事件在触发之前或至少在视图中看不到任何响应之前都有延迟。有什么办法可以减少或消除这种延迟?它同时发生在我的笔记本电脑和触摸屏面板上,因此我知道它不是特定于设备的。
在这种情况下,您有几个选择要做:
1)在HTML中将Observable
(Subject
,BehaviorSubject
或普通Observable
)与async
管道一起使用,而不是所使用的数据。
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)将ChangeDetectorRef注入组件的构造函数中并手动触发更改检测。
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(); }); } }
在这里您可以找到有关ChangeDetectionStrategy.OnPush的说明:https://blog.angular-university.io/onpush-change-detection-how-it-works/