When working with fromEvent and ViewChild I receive the following error in the terminal:
The last overload gave the following error. Argument of type
 ElementRef | undefined is not assignable to parameter of type
JQueryStyleEventEmitter<any, unknown> |
ArrayLike<JQueryStyleEventEmitter<any, unknown>>
I can’t understand or find a reason online why fromEvent is expecting a JQueryStyleEventEmitter type as the first argument in fromEvent?
My rxjs version: 7.5.7
From the rxjs docs:
Target : The DOM EventTarget, Node.js EventEmitter, JQuery-like event target,
NodeList or HTMLCollection to attach the event handler to.
export class AppComponent implements AfterViewInit{
@ViewChild('startPolling', { static: false }) startButton: ElementRef | undefined;
startClick$: any;
ngAfterViewInit() {
this.startClick$ = fromEvent(this.startButton, 'click');
}
}
>Solution :
You should use this.startButton.nativeElement to return the native DOM element as the first argument for fromEvent.
And you can use the ! exclamation mark as a replacement for the declaration of startButton with the type ElementRef | undefined.
@ViewChild('startPolling', { static: false }) startButton!: ElementRef;
ngAfterViewInit() {
this.startClick$ = fromEvent(this.startButton.nativeElement, 'click');
}
Reference: Create Observable from Event using FromEvent in Angular