I don't seem to be able to set focus on a input field in dynamically added FormGroup:
addNewRow(){
(<FormArray>this.modalForm.get('group1')).push(this.makeNewRow());
// here I would like to set a focus to the first input field
// say, it is named 'textField'
// but <FormControl> nor [<AbstractControl>][1] dont seem to provide
// either a method to set focus or to access the native element
// to act upon
}
How do I set focus to angular2 FormControl or AbstractControl?
For Angular 5, combining all of the above answers as follows:
Component relevant code:
The Template logic Looks like this:
In my template I add a record on blur, but you can just as easily set up a button to dynamically add the next input field. The important part is that with this code, the new element gets the focus as desired.
Let me know what you think
This is the safe method recommend by angular
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
orAbstractControl
, 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 throughViewChildren
(of which the API docs are non-existent currently, 2016-12-16).In your component class:
If you wanted to focus on the last child...
this.rows.last().nativeElement.focus()
And in your template something like:
EDIT:
I actually found a CodePen of someone doing what you're looking for https://codepen.io/souldreamer/pen/QydMNG