I\'m dynamically creating inputs with *ngFor. So, I would like to set focus on the last created input. Could someone help me?
This is my
There are multiple ways to do it but this code is just using template
U can do it with ngFor last like this
<ng-container *ngFor="let item of [1,2,3]; last as isLast" >
<input *ngIf="!isLast"type="text">
<ng-container *ngIf="isLast" >
<input type="text" #lastOne>
{{lastOne.focus()}}
</ng-container>
</ng-container>
another way to do it like this.
<ng-container *ngFor="let item of [1,2,3]" >
<input type="text" #lastOne>
{{lastOne.focus()}}
</ng-container>
feel free to choose
https://stackblitz.com/edit/angular-7-master-g3qsmt?file=src%2Fapp%2Fapp.component.html
Using ViewChildren and ViewChildren.changes. See this SO
I updated the stackblitz to focus using arrows keys. It's so simple than create a function
@ViewChildren('input') inputs: QueryList<ElementRef> //<--here declare our "inputs"
focusElement(index:number){
const input=this.inputs.find((x,i)=>i==index)
if (input)
input.nativeElement.focus()
}
And in the .html we ise keydown.arrowUp and keydown.arrowDown
<p *ngFor="let el of elements;let i=index">
<input #input (keydown.arrowUp)="focusElement(i-1)"
(keydown.arrowDown)="focusElement(i+1)" >
</p>
Updated, as Victor comments below, there's a problem when you has no items. It's because I forget check if there are inputs. So, when subscribe to inputs.changes
we need check it
this.inputs.changes.pipe(takeWhile(()=>this.alive)).subscribe(() => {
if (this.inputs.length) //<--add this "if"
this.inputs.last.nativeElement.focus()
})