【发布时间】:2021-09-18 03:37:43
【问题描述】:
为了减少变更检测,我们将 hostlistener 替换为来自 RXJS 的事件和 angular 的 runoutside。
这就是我的角度代码的样子
ngOnInit() {
this.windowKeyDown();
// this.subject$ = this.subject.asObservable();
}
constructor(private _ngZone: NgZone) {}
//@HostListener('window:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
console.log('handle key fired');
this.keypressed = event.key;
this.iskeyPressed = true;
}
windowKeyDown() {
console.log('windowKeyDown');
fromEvent(window, 'keydown')
.pipe(this.outsideZone(this._ngZone))
.subscribe(event => this.handleKeyboardEvent(<KeyboardEvent>event));
}
outsideZone<T>(zone: NgZone) {
return function(source: Observable<T>) {
return new Observable(observer => {
let sub: Subscription;
zone.runOutsideAngular(() => {
sub = source.subscribe(observer);
});
return sub;
});
};
}
和 HTML 绑定是:
<h2>keypressed: {{keypressed}}</h2>
<h2>iskeyPressed: {{iskeyPressed}}</h2>
在这个绑定变量中它自己现在没有更新,你能指导一下我的代码有什么问题吗?
重现的最小步骤:https://stackblitz.com/edit/keypress-example-vu3mej?file=app%2Fapp.component.html
【问题讨论】:
标签: javascript angular rxjs angular2-template