【问题标题】:How to add action on enter in angular如何在角度输入时添加动作
【发布时间】:2019-07-22 22:17:15
【问题描述】:

我是 Angular 新手,我需要帮助。我需要在键盘上的回车按钮上添加操作...因此,当用户在输入字段中输入内容并决定单击回车而不是使用鼠标时,必须具有相同的结果...这意味着必须通过单击来调用此函数输入...这对你们来说足够了,所以你可以给我一些答案吗? 谢谢:)

  <mat-form-field>
    <input
      matInput
      #filterName
      placeholder="Name"
      type="text"
      name="locationName"
      id="locationName"
    />
  </mat-form-field>

  <mat-form-field>
    <input
      matInput
      #filterStationType
      placeholder="Type"
      type="text"
      name="stationType"
      id="stationType"
    />
  </mat-form-field>

【问题讨论】:

    标签: javascript angular angular6


    【解决方案1】:

    1) 使用 import import { Component, HostListener } from '@angular/core'; 2)使用装饰器@HostListener:

    @HostListener('document:keydown', ['$event'])
      public KeyEvent(event: KeyboardEvent): void {
        if (event.key === 'Enter') {
          this.doSomething();
        }
    

    【讨论】:

      【解决方案2】:

      在你的组件的类定义中,你可以添加

      @HostListener("window:keyup.enter") onKeyUp() {
              // do something here
      }
      

      这会向该组件添加一个事件侦听器,该事件侦听器会在释放回车键时触发并执行。在正文中填写您希望在此事件中发生的事情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-06
        • 2017-01-26
        • 1970-01-01
        • 2018-05-04
        • 1970-01-01
        • 1970-01-01
        • 2021-05-01
        • 2017-09-09
        相关资源
        最近更新 更多