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 css style of 100% height and width). It's 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 don't show the component code, it does not matter for this question (afaik). This is working, but only if I actively select a button or the date-picker in advance (aka a control element). Is there a possibility to extend the keybinding to the whole div (i.e. if I just click somewhere on the site). Sorry for my lack of understanding the DOM and thanks for any push in the right direction.
If what you want is to detect key events on the whole page what you need is probably to add @HostListener to your component. It is gona let you manage events in the whole page/window.
Seeing an example.
import { Component, HostListener } from '@angular/core';
[your @Component stuff ..... ]
@HostListener("window:keydown", ['$event'])
onKeyDown(event:KeyboardEvent) {
console.log(`Pressed ${event.key}!`);
}
Furthermore could help you to know that when you want to refer specific items you can use ElementRef class and ViewChild by importing them from angular/core. Then manage DOM components as:
@ViewChild('DOM_Id') element: ElementRef;
Maybe it helps. Peace
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments