Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@HostBinding and @HostListener: what do they do and what are they for?

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?

like image 727
serlingpa Avatar asked Oct 16 '22 06:10

serlingpa


People also ask

What is HostBinding decorator doing in this directive?

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.

What is the use of HostListener in Angular?

HostListenerlink Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.

What is host in Angular directive?

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.

What is host element in Angular?

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.


1 Answers

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).

like image 207
Shai Reznik - HiRez.io Avatar answered Oct 17 '22 20:10

Shai Reznik - HiRez.io