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

I wrote my code as below. At the moment, the list item is selected only with a mouse click. I want to view the list even when I press the up and down arrows on the keyboard. How to achieve this with 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;
}

}

+6
source share
2 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

+7
source

Source: https://habr.com/ru/post/1669607/


All Articles