0%

angular-host-listener

Introduction

HostListener is an Angular Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.

What is a Host?

先看一下Host的含义,Host是指Directive或者Component的宿主元素,假设有一个ProductComponent组件,它的模板如下:

1
2
3
4
5
6
7
8
9
10
import {Component} from '@angular/core';

@Component({
selector: 'app-product',
template: `
<div>Product</div>
`,
})
export class ProductComponent {
}

我们在app.component.html中使用ProductComponent组件,代码如下:在这里,app-product就是ProductComponent的Host。

1
<app-product></app-product>

Render后的DOM结构如下:

1
2
3
<app-product>
<div>Product</div>
</app-product>

也可以这样理解,一个组件(指令)的Host就是在使用组件(指令)时,它们的选择器对应的元素。

See here for details.

Here is an example of using HostListener to listen for the click event on a button element:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import {Component, HostListener} from '@angular/core';

@Component({
selector: 'app-test',
standalone: true,
imports: [],
template: `
<button>Click me</button>
`,
})
export class TestComponent {
@HostListener('click')
onClick() {
console.log('Button clicked');
}
}

The above code is equivalent to the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import {Component, HostListener} from '@angular/core';

@Component({
selector: 'app-test',
standalone: true,
imports: [],
template: `
<button (click)="onClick()">Click me</button>
`,
})
export class TestComponent {
onClick() {
console.log('Button clicked');
}
}

HostListener is a more powerful way to listen for events because it allows you to listen for events on any element, not just the element that the HostListener is attached to. For example, you can listen for the events from document or window object.

  • document:click
  • window:keydown
  • window:scroll
  • window:resize
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import {Component, HostListener} from '@angular/core';

@Component({
selector: 'app-test',
standalone: true,
imports: [],
template: `
<button (click)="onClick()">Click me</button>
`,
})
export class TestComponent {
onClick() {
console.log('Button clicked');
}

@HostListener('document:click', ['$event'])
documentClick(event: MouseEvent) {
console.log(`Document clicked at (${event.clientX}, ${event.clientY})`);
}

@HostListener('window:keydown', ['$event'])
keydown(event: KeyboardEvent) {
console.log(`event.key: ${event.key} was pressed`);
}

@HostListener('window:scroll', ['$event'])
onScroll(event: Event) {
console.log(`Window scrolled`);
}

@HostListener('window:resize', ['$event'])
onResize(event: Event) {
console.log(`Window resized`);
}
}

References

https://angular.dev/api/core/HostListener?tab=usage-notes