Keyboard events

You can track keyboard interactions by listening to various keyboard events. The keypress event tells you that a button is clicked; if you have a listener attached to it, the listener is fired. You can attach keyboard events in the same way that we attached mouse events:

<div class="container" (keypress)="showKey($event)" tabindex="1">  ...  <div class="key-bg" *ngIf="keyPressed">    <h1>{{key}}</h1>  </div><div>

The element with the key-bg class is shown when a key is pressed; it displays the exact key we pressed, which is held in the key property. The keyPressed property is a Boolean that we set to true when a key is pressed.

The event fires the showKey listener; let's implement it:

import { Component } from '@angular/core';

Get TypeScript 2.x for Angular Developers now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.