问题
我使用了 ngrx 的 fromEvent 操作符从 2 个输入文本框创建了 Observable,我使用的是文档作为目标,这很好,但现在我想只针对一个输入文本框进行操作。我不确定该使用什么来替代 document 来指定只有一个输入文本框。
我已经尝试过的方式来获取目标
- 使用 document.getElementByID('someID')
- 使用 ElementRef
- 使用 document.querySelector('someID')
代码
import { Component } from '@angular/core';
import { fromEvent } from 'rxjs';
@Component({
selector: 'my-app',
template: `<input type="text">
<input type="text">`
})
export class AppComponent {
ngOnInit() {
fromEvent(document, 'keyup')
.subscribe(res => console.log(res.target.value));
}
}
提前感谢你的帮助。
ngAfterViewInit
中访问@ViewChild
属性,因为它们是在视图初始化后设置的,前提是该元素没有ngIf/ngFor
指令。 - Safal Pillai