Angular 2 - Subscribing to the Observable.fromEvent error: "Invalid event target"

I get a weird error when trying to sign up for an Observable.

Here is the version of the code below that presents the problem:

import {Component, Input, OnInit, ViewChild} from '@angular/core'; import Rx from 'rxjs/Rx'; @Component({ selector: 'action-overview-description', template: require('./actionOverviewDescription.html') }) export class ActionOverviewDescription { @ViewChild('button') button; constructor() {} ngOnInit() { let buttonStream$ = Rx.Observable.fromEvent(this.button, 'click') .subscribe(res => console.log(res)); } } 
 <button #input>Button</button> 

The error I get in the console is:

Invalid event target

Error when it ONLY appears when I subscribe to a stream. If I create it, but do not subscribe, there are no errors. If I console.log the stream seems to have a subscription member.

I tried the error in googling, but I can not find anywhere where it is explained.

I think I'm using Rxjs 4.0.5 (according to npm rxjs --version).

+17
angular observable rxjs
source share
1 answer

The problem is which lifecycle hook you are using. The item is not yet ngOnInit in the DOM when ngOnInit . 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)); } } 
+39
source share

All Articles