Set focus on dynamically created input on Angular

后端 未结 2 1412
你的背包
你的背包 2021-01-28 01:51

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

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-28 02:54

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

提交回复
热议问题