Angular 2 - subscribing to Observable.fromEvent error: "Invalid event target"
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));
}
}
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));
}
}