如何使用 angular2 和 angular rxjs 观察 mousemoves
How to observe mousemoves with angular2 and angular rxjs
我有以下内容:
angular2(NameCmp)
import {
OnInit, Component, ChangeDetectionStrategy, ViewChild, ElementRef,
AfterViewInit
} from 'angular2/core'
import {Observable} from 'rxjs/Observable';
..
export class NameCmp implements AfterViewInit{
....
@ViewChild('card')
card: ElementRef;
mouseMoves$: Observable<MouseEvent>;
ngAfterViewInit(): void {
this.mouseMoves$ = Observable.fromEvent(this.card.nativeElement, 'mousemove');
this.mouseMoves$.subscribe( event => console.log('logging mousemove'));
console.log('after view init')
}
.html
...
<md-card #card>
<md-card-content>
<md-input
required
placeholder = "Title"
[ngFormControl] = "titleCtrl"></md-input>
</md-card-content>
</md-card>
然而,尽管 console.log('after view init')
打印到控制台,console.log('logging mousemove'));
语句却没有。
谢谢
你的代码没问题,你只需要导入fromEvent
import "rxjs/add/observable/fromEvent";
或从 Rx
导入 Observable
import {Observable} from 'rxjs/Rx';
勾选这个plunk
更新
为了获得引用组件的 nativeElement 的引用。例如获取md-card
的nativeElement,需要将对象{read:ElementRef}
传给ViewChild()
@ViewChild('card', {read: ElementRef})
我有以下内容:
angular2(NameCmp)
import {
OnInit, Component, ChangeDetectionStrategy, ViewChild, ElementRef,
AfterViewInit
} from 'angular2/core'
import {Observable} from 'rxjs/Observable';
..
export class NameCmp implements AfterViewInit{
....
@ViewChild('card')
card: ElementRef;
mouseMoves$: Observable<MouseEvent>;
ngAfterViewInit(): void {
this.mouseMoves$ = Observable.fromEvent(this.card.nativeElement, 'mousemove');
this.mouseMoves$.subscribe( event => console.log('logging mousemove'));
console.log('after view init')
}
.html
...
<md-card #card>
<md-card-content>
<md-input
required
placeholder = "Title"
[ngFormControl] = "titleCtrl"></md-input>
</md-card-content>
</md-card>
然而,尽管 console.log('after view init')
打印到控制台,console.log('logging mousemove'));
语句却没有。
谢谢
你的代码没问题,你只需要导入fromEvent
import "rxjs/add/observable/fromEvent";
或从 Rx
Observable
import {Observable} from 'rxjs/Rx';
勾选这个plunk
更新
为了获得引用组件的 nativeElement 的引用。例如获取md-card
的nativeElement,需要将对象{read:ElementRef}
传给ViewChild()
@ViewChild('card', {read: ElementRef})