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

前端 未结 2 1014
无人共我
无人共我 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: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: ''
    })
    export class ActionOverviewDescription implements AfterViewInit {
      @ViewChild('input') button: ElementRef;
    
      ngAfterViewInit() {
        let buttonStream$ = Observable.fromEvent(this.button.nativeElement, 'click')
            .subscribe(res => console.log(res));
    
      }
    }
    

提交回复
热议问题