Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus on ul li after ngIf performed

Tags:

angular

I have div with <ul> and <li> that show after ngIf performed as below:

<input type="text" />
<button (click)="ShowDropDown=true;">Show</button>
<div *ngIf="ShowDropDown">
  <ul>
    <li (mousedown)="...">...</li>
    <li (mousedown)="...">...</li>
    <li (mousedown)="...">...</li>
  </ul>
</div>

I need to set focus on the very first element of <li> after clicking on the Show button.

like image 571
Janith Widarshana Avatar asked Dec 03 '22 21:12

Janith Widarshana


2 Answers

<input type="text" #myInput />
<button (click)="ShowDropDown=true;">Show</button>
<div *ngIf="ShowDropDown">
  {{ myInput.focus() }}
  <ul>
    <li (mousedown)="...">...</li>
    <li (mousedown)="...">...</li>
    <li (mousedown)="...">...</li>
  </ul>
</div>

put attention on {{ myInput.focus() }} inside ngIf and #myInput inside the input

like image 132
Sergey Gurin Avatar answered Dec 29 '22 08:12

Sergey Gurin


For setting focus on element like div, li etc., you need to set a tabindex attribute for them. Here is how you can set the focus on button click:

Change your component html to this:

<button (click)="showDropDown()">Show</button>
<div *ngIf="toggleDropDown">
  <ul>
    <li #firstLi tabindex="0">...</li>
    <li >...</li>
    <li >...</li>  
  </ul>
</div>

... and in your component class to:

toggleDropDown: boolean = false;
  @ViewChild('firstLi') firstLi:ElementRef;
  public showDropDown(){
      this.toggleDropDown=true
      setTimeout(()=>{
        this.firstLi.nativeElement.focus();
      },10);
  }

Here is a working plunker: DEMO

like image 21
Faisal Avatar answered Dec 29 '22 09:12

Faisal