Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Native Element function to focus is not working

Tags:

angular

I was trying to autofocus on an input element on click of a button. Please see the typescript

@ViewChild('envFilter') envFilter: ElementRef;
onFilterSelect() {
    this.envFilter.nativeElement.focus();
}

On the HTML side I have the following.

<div [ngClass]="isFilterVisible ? 'item item1' : 'item item1 hide'">
     <div [@filterAnimation]="isFilterVisible" class="filterWrapper">
          <input type="text" class="envFilter" [(ngModel)]="envFilterValue" (keyup)="envFilterChanged(envFilterValue)" #envFilter />
            <!-- {{ envFilter.focus() }} -->
      </div>
</div>

On using {{ envFilter.focus() }} I'am able to focus on the field but I'm not able to focus on any other input boxes

Missed a small bit of HTML here

<div class="pull-right  filter-down filter-down-div item item2">
     <i *ngIf=" envs.length !=0" role="button" (click)="onFilterSelect(envFilter)" class="filter-icon fas fa-search"
            [ngClass]="{'active': isFilterVisible ,'disabled':!isFilterVisible}" role="button"></i>
</div>

This segment is basically a search button which on click calls the previous onFilterSelect() function

Is there some wrong in my code. Why is the auto-focus not working

like image 620
Manesh Avatar asked Jul 12 '26 14:07

Manesh


1 Answers

I don't know if your problem is this, but remember that if you have the input in a *ngIf, you need give Angular a "breath" (using, e.g. setTimeout)

A simple example, imagine you have

<input *ngIf="visible" [(ngModel)]="variable" #myInput>
<button (click)="focus()">click</button>

You have

visible:boolean=false
@ViewChild('myInput') myinput:ElementRef

If you write

/**NO WORK***/
focus()
{
  this.visible=true;
  this.myinput.nativeElement.focus() //<--NOT YET in the DOM
}

You need write something like

focus()
{
  this.visible=true;
  setTimeout(()=>{
      this.myinput.nativeElement.focus()
  })
}

This setTimeout, make that first repaint, and after, makes the focus

like image 190
Eliseo Avatar answered Jul 15 '26 04:07

Eliseo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!