Issue
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
Solution
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
Answered By - Eliseo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.