Angular の@HostListener の使い方

Angular の@HostListener の使い方

イベントハンドラに@HostListenerをつけると、ずっとイベントをリッスンしてくれます。

以下はブラウザのどこでもよいのでクリックした時にイベントハンドラが実行されるようにリッスンしています。

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  // イベントハンドラの上に@HostListenerを記述する
  @HostListener( 'document:click', [ '$event' ] )
  public onTest(event: Event) {
    alert('test');
  }
}

app.component.html

<p>test</p>

document.clickと記述することで、ブラウザのどこかをクリックするとイベントハンドラが実行されるようになります。HTML側では(click)などは一切書かなくても動作します。

イベントイベントハンドラ動作内容
@HostListener( ‘document:click’, [ ‘$event’ ] )ブラウザのどこかをクリック時
@HostListener( ‘document:mouseover’, [ ‘$event’ ] )ブラウザにマウスオーバー時
@HostListener( ‘window:resize’, [ ‘$event’ ] )ブラウザのリサイズ時

コメント

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