Open In App

HostListener Decorators in Angular 17

Decorators are declarative functions in Angular that are used to change classes, methods, or properties. They serve as a source of metadata that instructs Angular on how to handle a class.

What is HostListener Decorator?

The @HostListener decorator in Angular provides a convenient way to listen for events on the host element of a component. It allows to define event handlers directly within the component class. In order to listen to events on the host element of the directive or component, one uses Angular's @HostListener decorator. This decorator function takes an event name as a parameter. The related function is called by the host element when that event is fired.

Syntax :

@component({
selector: ['appExampleDirective']
})
export class ExampleDirective {
@HostListener('event') methodName() {
//code to execute when the event occurs
}
}

Features of HostListener

Uses of HostListener

Steps to Create Angular Project

Step 1: Create the angular project using the following command.

ng new app_name

Step 2: Open Your project and go to terminal to start the application.

ng serve

Folder Structure:


df

HostListener Decorators in Angular 17


Dependencies:

"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}

Example: This example shows the implementation of hostListners decorators.

<!-- app.component.html -->

<div style="text-align: left; 
    color: brown; background-color: yellowgreen">
    <h1>Welcome to learn about Decorators</h1>
</div>

<button [disabled]="buttonDisabled">Click me</button>
//app.component.ts

import { Component, HostListener } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet],
    templateUrl: './app.component.html',
    styleUrl: './app.component.css'
})
export class AppComponent {
    title = 'decorator';

    buttonDisabled = false;

    @HostListener('click', ['$event.target'])
    onClick(target: HTMLElement) {
        if (target.tagName === 'BUTTON') {
            this.toggleButton();
        }
    }

    toggleButton() {
        this.buttonDisabled = !this.buttonDisabled;
    }
}

Output :


test

Article Tags :