html list item selection with arrow keys in Angular 2

Viewed 9516

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?

3 Answers

Thanks all. I have implemented this to take care of scrolling it.

arrowkeyLocation = 0;
  keyDown(event: any) {
  
    if(event.keyCode=== 13){
     let valueEnterKey =this.serviceDropdown[this.arrowkeyLocation];

     console.log("valueEnterKey",valueEnterKey);
     this.dropDefaultVal1=valueEnterKey;
     this.boolval1 = !this.boolval1;
    }
   
    var listOfDropDownItemsService = document.getElementsByTagName('ul')[6];

    if (event.keyCode === 40 && this.arrowkeyLocation < this.serviceDropdown.length - 1) {
      // Arrow Down
      this.arrowkeyLocation++;
      listOfDropDownItemsService.scrollTop = listOfDropDownItemsService.scrollTop + 15;
    }
     else if (event.keyCode === 38 && this.arrowkeyLocation > 0) {
      // Arrow Up
      this.arrowkeyLocation--;
      listOfDropDownItemsService.scrollTop = listOfDropDownItemsService.scrollTop - 15;
    }

   
  }
Related