Angular 2 - subscribing to Observable.fromEvent error: “Invalid event target”

前端 未结 2 1012
无人共我
无人共我 2020-12-14 17:42

I am getting a weird error when trying to subscribe to an Observable.

Here is a watered down version of the code which presents the problem:

相关标签:
2条回答
  • 2020-12-14 18:15

    If you want to access it in ngOnInit event then you would have to use { static: true } property of ViewChild something like this:

    import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
    import { Observable, fromEvent } from 'rxjs';
    
    @Component({
      template: '<button #input>Button</button>'
    })
    export class ActionOverviewDescription implements OnInit {
      @ViewChild('input', { static: true }) button: ElementRef;
    
      ngOnInit() {
        let buttonStream$ = Observable.fromEvent(this.button.nativeElement, 'click')
            .subscribe(res => console.log(res));
    
      }
    }
    
    0 讨论(0)
  • 2020-12-14 18:25

    The problem is the lifecycle hook you're using. The element is not yet creating in DOM when ngOnInit is called. Instead, you should use ngAfterViewInit.

    Could you try the following code:

    import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
    import { Observable, fromEvent } from 'rxjs';
    
    @Component({
      template: '<button #input>Button</button>'
    })
    export class ActionOverviewDescription implements AfterViewInit {
      @ViewChild('input') button: ElementRef;
    
      ngAfterViewInit() {
        let buttonStream$ = Observable.fromEvent(this.button.nativeElement, 'click')
            .subscribe(res => console.log(res));
    
      }
    }
    
    0 讨论(0)
提交回复
热议问题