0

I have an Angular 2+ app which has a component with an array and I have an ngFor which I show and I bind with [(ngModel)] to the elements of the array. I have a button which adds on click and empty record to the last element of the array to edit. What I want is to focus to the input field which is at the last element of the array. I think I need to use ViewChildren for that (because it is an array) and not ViewChild. Most tutorials that I have found use ViewChild to focus to a single element. What I want is to focus to the input field of each new record.

man
  • 15
  • 4
  • May be this can help u https://stackoverflow.com/questions/62786384/set-focus-on-dynamically-created-input-on-angular/62788343#62788343 – hanan Jul 08 '20 at 05:53

1 Answers1

0

Yes you would use ViewChildren for this. ViewChildren returns a QueryList, which has an accessor method for the first and last items in the QueryList intuitively called last. If your ViewChildren variable is called children, you can get the last element with children.last

Putting it all together,

children.last.nativeElement.focus()

TheBatman
  • 770
  • 4
  • 10