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
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 //<--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
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()
})