【问题标题】:How to target an HTML element using rxjs fromEvent in Angular 6如何在 Angular 6 中使用 rxjs fromEvent 定位 HTML 元素
【发布时间】:2019-02-10 10:55:12
【问题描述】:

问题

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

到目前为止我为实现目标所做的工作

  • 使用 document.getElementByID('someID')
  • 使用 ElementRef
  • 使用过的 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】:

    如果您使用 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();
      }
    }
    

    注意@ViewChild 声明中的{static: true}: 它使 Angular 知道生命周期“OnInit”中已经引用的元素。

    【讨论】:

      【解决方案2】:

      你可以给你想观察的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 供您参考。

      【讨论】:

      • @ViewChild 属性应该在ngAfterViewInit 中访问,因为它们是在视图初始化之后设置的,前提是元素没有 ngIf/ngFor 指令。
      • @SafalPillai,这是有道理的。非常感谢您指出。我已经更新了我的答案。 :)
      猜你喜欢
      • 1970-01-01
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 2019-11-17
      • 2021-09-19
      • 1970-01-01
      相关资源
      最近更新 更多