Which is better between @HostListener and Renderer.listen?
I'm building a simple canvas drag n drop application similar to http://rectangleworld.com/demos/SimpleDragging/SimpleDragging. For mouseevent listeners, I used @Hostlistener because for me it has simpler syntax and it is working. There's another way to achieve it with Renderer.listen. But I can't decide to use it over hostlistener. Can anyone explain and tell which is better between @HostListener
and Renderer.listen
?
My answer might 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 the Event
to listen to ( click
, keydown
, keyup
, etc.) and finally the Callback Function
In code, here's what happened in listen()
function (*):
listen(renderElement: any, name: string, callback: Function): Function {
return this._rootRenderer.eventManager.addEventListener(renderElement, name, decoratePreventDefault(callback));
}
So the problem would be now just specifying the Element
(easy) but people usually use elementRef.nativeElement
which is a security risk according to Angular Documentation, so be sure before using it!. Another problem (will not really) is that the Renderer
class is experimental (Check its Documentation), I faced a problem with setText()
it used to work in the RC but now it's not.. so yeah test the Renderer
functionalities good before using them. aaaaaaand when you're done you need to unbind the event manually!, Check this answer for more.
But I would keep an eye on the Renderer
status because the main purpose of it is rendering the elements on any environment (Web, Node, Mobiles, .etc) with one code base, so yeah let's hope it become stable in the future.
@HostListener()
HostListener
is a great decorator and shows how great Angular2 works with TypeScript, you only need to set the event and the value to passed to the callback function (the function under it), and usually people just pass [$event]
so you can have more control on the validations inside the function and YES you don't need to set the Element
since it listens to the document
so it's doing a delegation
to the events and you don't access the DOM
and your app will be secured. Also you don't need the unbind the events, Angular will do it for you.
Check this article for a working example
Hope my answer help, remember Angular is still evolving so some things might change.
References:
*: Hacking Angular2: Binding Multiple DOM Events by Sean T. Larkin
链接地址: http://www.djcxy.com/p/94000.html上一篇: 加入空后缀