Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html list item selection with arrow keys in Angular 2

I am trying to select li's via arrow keys, but am running into issues.

I tried following the answer here, but my li's never become selected.

For the following code, I'm just trying to get (keydown) to work.

Here is my:

landingpage.component.html

<div class="searchArea">
  <input type="text" autoComplete="off" (keydown)="keyDown($event)" placeholder={{backgroundPlaceholder.info.placeholderText}} [(ngModel)]="keystroke"
    (ngModelChange)="getKey($event)">
  <div class="results-list">
    <li *ngFor="let list of shows; let i = index" [class.active]="i == {{arrowkeyLocation}}">
      <span class="result">{{list.show}}</span>
    </li>
  </div>
</div>

landingpage.component.ts

arrowkeyLocation = 0;

 keyDown(event) {
   return this.arrowkeyLocation++; 
 } 

As-is, nothing is selected when I press the downkey. I'm pretty sure the problem lied within my html [class.active], but I'm not sure how to resolve it.

How can I select li elements via the arrow keys?

like image 920
Edon Avatar asked Feb 19 '26 10:02

Edon


1 Answers

If you want to only select the list using arrow key, I think you need to change your landingpage.component.ts to something like this:

arrowkeyLocation = 0;

keyDown(event: KeyboardEvent) {
    switch (event.keyCode) {
        case 38: // this is the ascii of arrow up
                 this.arrowkeyLocation--;
                 break;
        case 40: // this is the ascii of arrow down
                 this.arrowkeyLocation++;
                 break;
    }
}

And in your html you need to change [class.active]="i == {{arrowkeyLocation}}" to [class.active]="i == arrowkeyLocation".. No need to use {{ and }} there.

like image 123
samAlvin Avatar answered Feb 20 '26 23:02

samAlvin