Angular2 Templates: how to bind keydown.arrow to whole div instead of just controls?

I have a simple navigator component with some buttons and a date picker subcomponent. Now the idea is that I can bind keydown.arrowleft

etc. For the whole div (which has a CSS style of 100% height and width). Its template looks like this:

<div id="ck-navigator" (keydown.arrowleft)="decrementDate(); 
    $event.preventDefault()" (keydown.arrowright)="incrementDate(); 
$event.preventDefault()">
    <button (click)="decrementDate()" class="fa fa-2x fa-chevron-left">
    </button>
    <ck-date-picker [date]="date" (dateChange)="changeDate($event)">
    </ck-date-picker>
    <button (click)="incrementDate()" class="fa fa-2x fa-chevron-right"></button>
</div>

      

I am not showing the component code, it doesn't matter for this question (afaik). This works, but only if I actively select a button or date picker in advance (aka control). Is it possible to extend the key binding to the entire div (i.e. if I just clicked somewhere on the site). Sorry for my misunderstanding of the DOM and thanks for any nudge in the right direction.

+3


source to share


2 answers


If you want to detect key events throughout the page, then you need to add an @HostListener to your component. This gona allows you to manage events across the entire page / window.

See example.

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

      

[your @Component stuff .....]



@HostListener("window:keydown", ['$event'])

 onKeyDown(event:KeyboardEvent) {

    console.log(`Pressed ${event.key}!`);
  }

      

Also, you can find out that when you want to refer to specific elements, you can use the ElementRef and ViewChild class by importing them from angular / core. Then manipulate the DOM components like:

@ViewChild('DOM_Id') element: ElementRef;

      

Maybe it helps. World

+4


source


The problem is your div is not focusing, so it doesn't respond to your keywords. Try adding an attribute tabindex="0"

to the div.



+4


source







All Articles