How to use @HostListener in Angular

How to use @HostListener in Angular

If you add @HostListener to your event handler, it will listen for events all the time.

The following listens for an event handler to be executed when clicked anywhere in the browser.

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  // Write @HostListener on top of the event handler
  @HostListener( 'document:click', [ '$event' ] )
  public onTest(event: Event) {
    alert('test');
  }
}

app.component.html

<p>test</p>

By writing document.click, an event handler will be executed when the user clicks anywhere in the browser.

On the HTML side, you do not need to write (click) at all.

Event Event handler operation details
@HostListener( ‘document:click’, [ ‘$event’ ] ) When clicking anywhere in the browser
@HostListener( ‘document:mouseover’, [ ‘$event’ ] ) On mouse-over in the browser
@HostListener( ‘window:resize’, [ ‘$event’ ] ) When the browser is resized

コメント

タイトルとURLをコピーしました