LoginSignup
6
8

More than 5 years have passed since last update.

Angularで、Componentにキーイベントを取得させる

Last updated at Posted at 2019-02-24

概要

Angularでちょっとしたコンポーネントを作ったところ、「ショートカットキー欲しいなー、でもcanvasのaddEventListenerよろしくコンポーネントにキーイベント追加する方法見つからないなー」と思ったのでググったところ、日本語の情報がない。
StackOverflowやら公式のAPIやらをあれこれ参考にしてうまく行ったので備忘に書く。
コンポーネントではなく画面全体のキーイベントを取得させたいならdocument.onkeyup等を使ってください。

手順

keyupについては以下の2つの両方をすればOK。多分他のkey系イベントでも使えると思われる。

  • Angular特有のkeyupを使ってキーイベントを受け取るにはフォーカス可能でなければならないので、ComponentにTabIndexを付与する
  • HostListenerデコレータを使ってkeyupイベントに対応するメソッドをComponentのメンバとして作成する

というわけで出来上がったのが以下のコード

src/app/example/example.component.ts
import { Component, HostBinding, HostListener } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {

  @HostBinding('tabIndex') tabIndex:string;//tabIndexを付与するため、ComponentにtabIndexをバインドするメンバを用意
  constructor() {
    this.tabIndex="0";//TabIndexを付与。これをしないとフォーカスできないのでコンポーネントに対するキーイベントを取得できない。
  }
  @HostListener('keyup',['$event'])//対応するイベントを第一引数に、その結果を渡す引数名を第二引数に指定
  onKeyUp(event:any) { //イベント取得時の処理を記述。メソッド名は自由。
    console.log(event);
  }
}

見えやすくするだけだけども一応cssも

src/app/example/example.component.css
/*
見やすくするためだけのCSSなので消してもOK
*/
p {
  background-color:#0000ff;
  height:100px;
}
:host {
  display:block;
  background-color:#ff0000;
  height:400px;
}

あとはng generate componentしたときのまんま

バージョン

前の記事を参照

参考

https://stackoverflow.com/questions/44758299/angular-2-keyup-enter-for-div-tag
https://qiita.com/yasshcy/items/b3147a2415ee390bde4a
https://angular.io/api/core/HostListener
前の記事

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8