# Angular 装饰器 HostListener 监听DOM事件

> Angular 装饰器 HostListener 监听DOM事件，本例监听回车键（Enter）与换行按键（Ctrl Enter）事件处理发送消息示例。

Author: DeathGhost
Published: 2020-04-17 17:45:47
Category: angular
Canonical: https://www.deathghost.cn/article/angular/71
Keywords: Angular, 装饰器, HostListener, @HostListener(), 监听, 侦听, DOM, 事件, 回车, 回车换行

一直用Angular前端框架做项目，UI借用第三方库，在处理过程中很少操作相关基础，更多是在业务层面上。

因此工作中遇到此类将其记录下来作为学习过程。

## @HostListener()装饰器

>
Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.

eventName: string  The DOM event to listen for.

args:  A set of arguments to pass to the handler method when the event occurs.

参考[这里](https://angular.io/api/core/HostListener)。

## 示例场景

聊天窗口发送消息按键，回车（Enter）发送消息，换行（Ctrl Enter）对其文本换行。

![Angular HostListener](https://www.deathghost.cn/public/upload/article/2020/04/17/1587123891863548.jpg)

Angular HostListener 监听回车事件

## 使用方法

在当前所需组件中从@angular/core导入HostListener

显示图如上述场景，按回车（Enter）键发送消息，按Ctrl Enter键换行输入消息。

![发送消息窗口示例图](https://www.deathghost.cn/public/upload/article/2020/04/17/1587124540261115.gif)

发送消息窗口示例图

import { Component, OnInit, HostListener, Input } from '@angular/core';
@HostListener('window:keydown', ['$event'])
handleKeyDown(event: KeyboardEvent) {
    if (event.ctrlKey && event.key === 'Enter') {
      if (this.inputValue.trim() === '') {
        return;
      }
      this.inputValue  = '\n';
    } else if (event.key === 'Enter') {
      event.preventDefault();
      if (this.inputValue.trim() === '') {
        return;
      }
      this.inputValue = '';
      console.log('发送消息');
    }
    if (event.type === 'click') {
      this.inputValue = '';
      console.log('发送消息');
      return;
    }
  }

## Related

- Previous: [Angular 管道之异步数据读取转换](https://www.deathghost.cn/article/angular/58)
- Next: [Angular自定义预加载策略](https://www.deathghost.cn/article/angular/88)
