angularangular-services

@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?


Solution

  • Have you checked these official docs?

    HostListener - Declares a host listener. Angular will invoke the decorated method when the host element emits the specified event.

    @HostListener - will listen to the event emitted by the host element that's declared with @HostListener.

    HostBinding - Declares a host property binding. Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive.

    @HostBinding - will bind the property to the host element, If a binding changes, HostBinding will update the host element.

    Here's a simple code example to help picture what this means:

    DEMO : Here's the demo live in plunker - "A simple example about @HostListener & @HostBinding"

    directives.ts

    import {Component,HostListener,Directive,HostBinding,Input} from '@angular/core';
    
    @Directive({selector: '[myDir]'})
    export class HostDirective {
        @HostBinding('attr.role') role = 'admin';
        @HostListener('click') onClick() {
            this.role= this.role === 'admin' ? 'guest' : 'admin';
        }
    }
    

    AppComponent.ts

    import { Component,ElementRef,ViewChild } from '@angular/core';
    import {HostDirective} from './directives';
    
    @Component({
        selector: 'my-app',
        template:
            `
            <p myDir>
                Host Element 
                <br><br>
            
                We have a (HostListener) listening to this host's 
                <b>click event</b> declared with @HostListener
            
                <br><br>
            
                And we have a (HostBinding) binding <b>the role property</b>
                to host element declared with @HostBinding 
                and checking host's property binding updates.
                
                If any property change is found I will update it.
            </p>
            
            <div>
                View this change in the DOM of the host element 
                by opening developer tools, clicking the host element in the UI. 
            
                The role attribute's changes will be visible in the DOM.
            </div> 
            `,
        directives: [HostDirective]
    })
    export class AppComponent {}