我已经开始探索 Angular2(我带着 Angular1 和一些 React 背景而来),但我遇到了一个问题。
我想将某些击键绑定到组件中的操作,因此我决定使用 Angular2 生命周期来绑定/取消绑定操作。
但是,如果我在 Mousetrap 回调中执行某些操作,它会起作用,但不会呈现,并且在运行摘要周期之前更改不可见。
我是否需要显式运行某些内容来更新视图
有人可以帮我弄清楚发生了什么事吗?
任何帮助将不胜感激。
import {Component} from 'angular2/core';
const Mousetrap = require('mousetrap');
@Component({
template: `<div>
Video template: Mode {{ mode }}
<input type="number" [(ngModel)]="mode"/>
</div>`
})
export class Video {
public mode: number;
constructor() {
this.mode = 0;
}
ngOnInit() {
console.log('hello Video component');
Mousetrap.bind('d', () => console.log('this.mode=', this.mode));
Mousetrap.bind('i', () => this.incrementMode()); // doesn't work
this.incrementMode(); // works
this.incrementMode(); // works
setTimeout(() => this.incrementMode(), 4000); // works
}
incrementMode() {
console.log('incMode', this.mode++);
};
ngOnDestroy() {
console.log('bye bye Video component');
Mousetrap.unbind(['d', 'i']);
}
}
虽然@Günter的答案是绝对正确的,但我想提出一个不同的解决方案。
问题在于Mousetrap
库是它创建它的实例角的外面zone (see here)。但是为了在每个异步事件之后触发更改检测,应该实例化实例角内zone。您有两种选择来实现此目的:
- 使用依赖注入:
bootstrap(App, [provide(Mousetrap, { useFactory: () => new Mousetrap() }) ]);
// ...
@Component({
selector: 'my-app',
// ...
})
export class App {
constructor(@Inject(Mousetrap) mousetrap) {
this.mousetrap = mousetrap;
// ...
}
//...
}
- 只需创建实例
Mousetrap
构造函数内部:
@Component({
selector: 'my-app',
// ...
})
export class App {
constructor() {
this.mousetrap = new Mousetrap();
// ...
}
//...
}
在这两种情况下,您都可以像这样使用 mousetrap 实例:
ngOnInit() {
this.mousetrap.bind('i', () => this.incrementMode()); // It works now!!!
// ...
}
现在你不需要使用ngZone.run()
在每一个bind
call。如果是依赖注入,你也可以使用这个mousetrap
应用程序的任何组件/服务中的实例(不仅在App
成分)。
See 这个笨蛋。我在那里使用依赖注入。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)