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.
<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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With