[英]How to target an HTML element using rxjs fromEvent in Angular 6
Issue问题
I have used ngrx fromEvent operator to create an Observable from 2 input text fields, I have used document as target which is fine, but now I want to target only one input field.我使用 ngrx fromEvent 运算符从 2 个输入文本字段创建了一个 Observable,我使用文档作为目标,这很好,但现在我只想定位一个输入字段。 I am not sure sure what to use instead of document to target only one input field.我不确定使用什么代替文档来仅定位一个输入字段。
What I have done so far to get the target到目前为止我为达到目标所做的一切
Code代码
StackBlits live editor StackBlits 实时编辑器
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));
}
}
Thanks for your help in advance.提前感谢您的帮助。
You can give the input
field that you want to observe, a template variable.您可以为要观察的input
字段提供模板变量。
You can use then use @ViewChild
to get access to that input
.您可以使用然后使用@ViewChild
来访问该input
。 And then use the nativeElement
property on it.然后在其上使用nativeElement
属性。
Now the nativeElement
property will only be accessible after the view has initialized.现在,只有在视图初始化后才能访问nativeElement
属性。 So you can use the AfterViewInit
Component Lifecycle Hook in order to access it.因此,您可以使用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));
}
}
Here's an Updated StackBlitz for your ref.这是供您参考的更新的 StackBlitz 。
If you're reading this with Angular 8+, the correct way to reference @ViewChild-elements while being able to use them in ngOnInit is this:如果您正在使用 Angular 8+ 阅读本文,则在能够在 ngOnInit 中使用它们的同时引用 @ViewChild-elements 的正确方法是:
import { Component, ViewChild, ElementRef, OnInit, OnDestroy } from '@angular/core';
import { fromEvent } from 'rxjs';
@Component({
selector: 'my-app',
template: `
<input #yourTarget type="text">
<input type="text">
`
})
export class AppComponent implements OnInit, OnDestroy {
@ViewChild('yourTarget', {static: true}) yourTarget: ElementRef;
subscriptions = new Subscription();
ngOnInit(): void {
subscriptions.add(
fromEvent(this.yourTarget.nativeElement, 'keyup')
.subscribe(res => console.log(res.target.value))
)
}
ngOnDestroy(): void {
subscriptions.unsubscribe();
}
}
Notice the {static: true}
inside the @ViewChild declaration: It causes Angular to know the referenced element already in the lifeCycle "OnInit".注意@ViewChild 声明中的{static: true}
:它使 Angular 知道生命周期“OnInit”中已经存在的引用元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.