I made this post back in December 2016, Angular has progressed significantly since then, so I’d make sure from other sources that this is still a legitimate way of doing things
You cannot set to a FormControl
or AbstractControl
, since they aren’t DOM elements. What you’d need to do is have an element reference to them, somehow, and call .focus()
on that. You can achieve this through ViewChildren
(of which the API docs are non-existent currently, 2016-12-16).
In your component class:
import { ElementRef, ViewChildren } from '@angular/core';
// ...imports and such
class MyComponent {
// other variables
@ViewChildren('formRow') rows: ElementRef;
// ...other code
addNewRow() {
// other stuff for adding a row
this.rows.first().nativeElement.focus();
}
}
If you wanted to focus on the last child…this.rows.last().nativeElement.focus()
And in your template something like:
<div #formRow *ngFor="let row in rows">
<!-- form row stuff -->
</div>
EDIT:
I actually found a CodePen of someone doing what you’re looking for https://codepen.io/souldreamer/pen/QydMNG