4

I'm making a custom search input like bellow

   <input type="text" (keyup)="search()">

   <ul>
      <li  *ngFor='let item of results'>{{item}}</li> // Angular2 syntax for repeating over my array
   </ul>


  search(){
       //do the search : 

      // then attach the resuls

      this.results = apiResponse;

  }

This is working and all good.

Now I'm wondering how I can implement the functionality where if user is focused in the input and there are some results bellow the input ( in the ul ) , then if he presses the down arrow key in the keyboard , I would want to change the focus of the input and jump over the result so user can press enter and pick on of them.

Like google or all the other search inputs do .

Forgive me if I can't explain it correctly , it's hard to explain though.

Thanks in advance.

EDIT :

After some google , realized I can capture the keydown , keycode and if the keycode is downkey , I can focus on the first li element , BUT , this is not working , even after setting the tabindex.

   <input tabindex="-1" type="text" (keyup)="search($event)">

   <ul tabindex="0">
      <li tabindex="{{i}}" *ngFor='let item of results ; let i = index'>{{item}}</li> // Angular2 syntax for repeating over my array
   </ul>


  search($event){
       //do the search : 

      // then attach the results;

      if($event.keykode===40)// on down key
      {
           let li = this._el.nativeElement.querySelectorAll('li')[0];
           // I've got the li here , it's good
           li.focus(); ----->>>>>>>> not working !!!!
          // we don't want to trigger api search any more , so returning 
         return ;
      }
      this.results = apiResponse;

  }

Even if I inspect the li element via chrome dev tools and do $0.focus() , nothing happens .!!

EDIT :

Adding screenshot of the list : enter image description here

This is a long list , it starts from 1 , not 11 (removed couple of lis to make the screenshot smaller).

  • @GünterZöchbauer , I expect to element to be focused , I have created some css :focus things for this ul and li s , and , normally it should be outlined . The focus is working with mouse , –  Jun 04 '16 at 10:40
  • I think it should work. Have you checked the `li.focus();` line is actually executed? – Günter Zöchbauer Jun 04 '16 at 10:42
  • @GünterZöchbauer , I know I can create a directive , which I actually had in my real code , but the problem is about the focus function , not with the code being ugly or not . This question is more about javascript than Angular2 anyway. –  Jun 04 '16 at 10:42
  • @GünterZöchbauer , like I said , the focus is not working even with chome dev tools . –  Jun 04 '16 at 10:43