'How to add event Listeners in Angular?
I am writing an app using Angular 6, trying yo listen to plotly_click events (Visualization library). How can i set up a listener?
The Angular is recommending to use the Renderer2
from API > @angular/core.
They are providing a listen
function which is supposed to start an event listener. But any way this is not really working, i can to listen to events on document | body
but not on specific DOM Element.
There's also the method addEventListener()
from EventManager
in API > @angular/platform-browser. But i am facing the same problem.
import {... , Renderer2 } from '@angular/core';
import { EventManager } from '@angular/platform-browser';
@Component({
selector: 'app-abc',
template: '<div id="myDiv">abcdefghjk</div>',
})
@ViewChild('myDiv') myDiv: ElementRef;
ngOnInit() {
this.renderer.listen(this.myDiv, 'click', (event) => console.log("Trying to listen to click event on that DIV"));
// Or i tried also to use the evenetManager method
this.eventManager.addEventListener(this.button, 'click', (event) => console.log("Trying to listen to click event on that DIV"));
}
This what i get as an error (I got the same error when using event Manager):
SummaryComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'listen' of undefined
at SummaryComponent.push../src/app/summary/summary.component.ts.SummaryComponent.ngOnInit (summary.component.ts:21)
at checkAndUpdateDirectiveInline (core.js:10105)
at checkAndUpdateNodeInline (core.js:11371)
at checkAndUpdateNode (core.js:11333)
at debugCheckAndUpdateNode (core.js:11970)
at debugCheckDirectivesFn (core.js:11930)
at Object.eval [as updateDirectives] (SummaryComponent_Host.ngfactory.js? [sm]:1)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:11922)
at checkAndUpdateView (core.js:11315)
at callViewAction (core.js:11556)
Solution 1:[1]
Another option is RxJS fromEvent creation operator
fromEvent(this.host.nativeElement, 'wheel') // here you can use any DOM element
.pipe(
throttleTime(150),
takeUntil(this.onDestroy$), // don`t forget to cleanup!
tap((e: WheelEvent)=> this.doFancyStuff(e.deltaY))
).subscribe()
Solution 2:[2]
You should register the listener after the view was initialized and not in the onInit()
method.
ngAfterViewInit() {
this.renderer.listen(this.myDiv, 'click', (event) => console.log("Trying to listen to click event on that DIV"));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | grigson |
Solution 2 | Dan Atkinson |