Angular 装饰器 HostListener 监听DOM事件

这篇文章发布于

DeathGhost 编辑, 归类于 angular » 当前评论 0 条。

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

一直用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.

参考这里

示例场景

聊天窗口发送消息按键,回车(Enter)发送消息,换行(Ctrl Enter)对其文本换行。

Angular HostListener
Angular HostListener 监听回车事件

使用方法

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

显示图如上述场景,按回车(Enter)键发送消息,按Ctrl Enter键换行输入消息。

发送消息窗口示例图
发送消息窗口示例图
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;
    }
  }

Angular 装饰器 HostListener @HostListener() 监听 侦听 DOM 事件 回车 回车换行

上一篇:

下一篇: