我正在对angular observable进行基本测试以观察文本框的keyup,我没有收到任何错误但订阅不能正常工作,所以没有任何东西进入控制台...
import {Component} from 'angular2/core';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'appobserve',
template: `
<b>Angular 2 Component Using Observables!</b>
> input id="search" type="text" name="search" class="form-control" >
`
})
export class ObserveComponent {
constructor() {
console.log('startedbbb');
var keyups = Observable.fromEvent($('#search'),'keyup');
keyups.subscribe(function(ev) { console.log("click", ev) });
}
}
答案 0 :(得分:7)
这是angular2,带有jquery,带有javascript,带有typescript,带有rx ..和一些格式奇怪的html。
function
,这会弄乱this
上下文jQuery
,只需在输入元素上添加一个角度(keyup)
侦听器EventEmitters
使用了observables)这将有效:
@Component({
selector: 'appobserve',
template: `
<b>Angular 2 Component Using Observables!</b>
<input type="text" name="search" class="form-control" (keyup)="onKeyUp($event)">
`
})
export class ObserveComponent {
constructor() {}
onKeyUp(event: KeyboardEvent): void {
console.log(event);
}
}
答案 1 :(得分:0)
如果您仍想在文本框的键盘上使用Observable:
import { Component, ViewChild } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
@Component({
selector: 'my-app',
template: `<input #searchbox type="text" name="search" class="form-control">`
})
export class AppComponent {
@ViewChild('searchbox') searchbox;
ngOnInit(){
Observable.fromEvent(this.searchbox.nativeElement, 'keyup')
.subscribe((event)=>console.log(event));
}
}