In my meanderings around the world wide interweb, and now especially the angular.io style docs, I find many references to @HostBinding
and @HostListener
. It seems they are quite fundamental, but unfortunately the documentation for them at the moment is a little sketchy.
Can anyone please explain what they are, how they work and give an example of their usage?
HostBindinglink Decorator that marks a DOM property as a host-binding property and supplies configuration metadata. Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive.
HostListenerlink Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.
The host property, as mentioned in the documentation. Maps class properties to host element bindings for properties, attributes, and events, using a set of key-value pairs. where the host element is the element/component you have attached your directive to.
To turn an Angular component into something rendered in the DOM you have to associate an Angular component with a DOM element. We call such elements host elements. A component can interact with its host DOM element in the following ways: It can listen to its events.
A quick tip that helps me remember what they do -
HostBinding('value') myValue;
is exactly the same as [value]="myValue"
And
HostListener('click') myClick(){ }
is exactly the same as (click)="myClick()"
HostBinding
and HostListener
are written in directives
and the other ones (...)
and [..]
are written inside templates (of components).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With