如何使用Angular 6中的rxjs fromEvent来定位HTML元素

问题描述 投票:1回答:1

问题

我已经使用ngrx fromEvent运算符从2个输入文本字段创建一个Observable,我已经使用document作为目标,这很好,但现在我想只定位一个输入字段。我不确定使用什么代替文档来仅定位一个输入字段。

到目前为止我做了什么来达到目标

  • 使用document.getElementByID('someID')
  • 使用的ElementRef
  • used document.querySelector('someID')

StackBlits live editor

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));
  }
}

感谢您的帮助。

angular rxjs angular6 rxjs6
1个回答
4
投票

您可以给出要观察的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

© www.soinside.com 2019 - 2024. All rights reserved.