问题
我已经使用ngrx fromEvent运算符从2个输入文本字段创建一个Observable,我已经使用document作为目标,这很好,但现在我想只定位一个输入字段。我不确定使用什么代替文档来仅定位一个输入字段。
到目前为止我做了什么来达到目标
码
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));
}
}
感谢您的帮助。
您可以给出要观察的input
字段,模板变量。
然后你可以使用@ViewChild
来访问那个input
。然后使用nativeElement
属性。
现在只有在视图初始化后才能访问nativeElement
属性。因此,您可以使用AfterViewInit
组件生命周期挂钩来访问它。
import { Component, ViewChild, ElementRef } from '@angular/core';
import { fromEvent } from 'rxjs';
@Component({
selector: 'my-app',
template: `<input #toTarget type="text">
<input type="text">`
})
export class AppComponent {
@ViewChild('toTarget') toTarget: ElementRef;
ngAfterViewInit() {
fromEvent(this.toTarget.nativeElement, 'keyup')
.subscribe(res => console.log(res.target.value));
}
}
这是你的参考的Updated StackBlitz。