Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add event for key left and right in angular2?

Tags:

angular

I have written my code as mentioned below. As of now, the list item is selected only on mouse click. I want to traverse the list even when I press up and down arrow in keyboard. How to achieve this using angular2?

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

export class Hero {
name: string;
}

const HEROES: Hero[] = [
{ name: 'STWX1' },
{ name: 'STWX2' },
{ name: 'STWX3' },
{ name: 'STWX4' }
];

@Component({
selector: 'my-app',
template: `
    <div style="display: inline-block; width = 200px; ">
        <ul class="heroes">
            <li *ngFor="let hero of heroes" (click)="onSelect(hero)"
                [class.selected]="hero === selectedHero">
                 <p>{{hero.name}}</p>
            </li>
       </ul>
   </div>'

, styles: [...] })

export class AppComponent  {
name = 'Angular1';
testRequestId = '3224';
heroes = HEROES;
selectedHero: Hero;

goToDivClick() {
    return HEROES;
}

onSelect(hero: Hero): void {
    this.selectedHero = hero;
}

}

like image 377
test Avatar asked Feb 13 '17 16:02

test


People also ask

What is Keydown enter event?

The keydown event is fired when a key is pressed. Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

What is KeyUp and Keydown in angular?

The KeyDown event is triggered when the user presses a Key. 2. The KeyUp event is triggered when the user releases a Key. 3. The KeyPress event is triggered when the user presses & releases a Key.

What is Keydown enter in angular?

The ng-keydown directive tells AngularJS what to do when the keyboard is used on the specific HTML element. The ng-keydown directive from AngularJS will not override the element's original onkeydown event, both will be executed.


1 Answers

<li *ngFor="let hero of heroes;let index=index" 
  [style.background-color]="index === selectedIndex ? 'yellow' : null"
  (click)="onSelect(hero)" 
  (keydown.ArrowLeft)="onLeft($event)" (keydown.ArrowRight)="onRight($event)"
  (keydown.ArrowUp)="onUp($event)" (keydown.ArrowDown)="onDown($event)"

See also https://github.com/angular/angular/blob/630d93150a58581a0d474ebf1befb5d09b6813c5/modules/angular2/src/platform/browser/browser_adapter.dart

like image 161
Günter Zöchbauer Avatar answered Oct 17 '22 12:10

Günter Zöchbauer