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.
Asked
Active
Viewed 797 times
1 Answers
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