Search code examples
angularangular6angular8

is it possible to set focus for element?


I have two element on the page:

 <input tabindex="0" type="text" (keydown)="keydownInputSearch($event)" (click)="showSearchResultContent = !showSearchResultContent" #inputSearch>

And block:

 <div #searchList class="SearchList" *ngIf="showSearchResult()" tabindex="-1"></div>

Problem is when block #searchLis is exist I can not set focus back to #inputSearch.

I have tried:

 this.inputSearch.nativeElement.focus();

No errors, no effect. I suppose problem is that #searchList has tabindex="-1" and #inputSearchhas less: tabindex="0".

But by defaul input should have focus automatically.


Solution

  • You're almost there. Just focus on the input in ngAfterViewInit

     ngAfterViewInit() {
       this.inputSearch.nativeElement.focus();
     }
    

    Stackblitz: https://stackblitz.com/edit/hello-angular-6-1svrgt