My answer may not be the best, but here's what I got.
Renderer.listen ()
When it comes to Renderer.listen()
, you need to pass the Element
you want to detect, then an Event
to listen for ( click
, keydown
, keyup
, etc.) and finally a Function
Callback
In the code, what happened in listen()
function (*):
listen(renderElement: any, name: string, callback: Function): Function { return this._rootRenderer.eventManager.addEventListener(renderElement, name, decoratePreventDefault(callback)); }
Thus, the problem will now simply indicate Element
(simple), but people usually use elementRef.nativeElement
, which is a security risk according to the Angular Documentation , so be sure to use it !. Another problem (actually not) is that the Renderer
class is experimental ( Check its documentation ), I had a problem with setText()
it worked in RC, but now it is not .. so give a test to the Renderer
functions well before using them. aaaaaaand, when you are done, you need to cancel the event manually !, Check this answer for more .
But I would keep an eye on Renderer
status, because the main goal of this is to render elements in any environment (Web, Node, Mobiles, .etc) with one code base, so let's hope become stable in the future.
@HostListener ()
HostListener
is a great decorator and shows how Angular2 works with TypeScript, you only need to set the event and the value passed to the callback function (the function below it), and usually people just pass [$event]
so you can have more control over the checks inside the function. and YES you donโt need to install Element
as it listens to document
, so it does delegation
for events and you donโt get access to the DOM
and your application will be protected. Also you do not need to unleash events, Angular will do it for you.
Check out this article for a working example.
Hope my answer helps, remember that Angular is still evolving, so some things may change.
Literature:
*: Hack Angular2: binding of several DOM events of Sean T. Larkin