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.
source to share
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
source to share