I'm working with a template form component with angular2 and I cannot get to set the focus in my firstName input element after submit the form. The form is reseted fine but no way of setting focus.
This is my component code:
export class TemplateFormComponent {
@ViewChild('f') form: any;
onSubmit() {
if (this.form.valid) {
console.log("Form Submitted!");
this.form.reset();
this.form.controls.firstName.focus();
}
}
}
and my template code:
<form novalidate autocomplete="off" #f="ngForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>First Name</label>
<input type="text"
class="form-control"
name="firstName"
[(ngModel)]="model.firstName"
required
#firstName="ngModel">
</div>
</form>
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.
To clear an input field after submitting: Add a click event listener to a button. When the button is clicked, set the input field's value to an empty string. Setting the field's value to an empty string resets the input.
The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.
To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.
On your view, set a reference to the input field you want to focus (you already have that with #firstName
).
Then, on your component code, create an access to it with @ViewChild:
@ViewChild('firstName') firstNameRef: ElementRef;
And finally, right after reseting the form:
this.firstNameRef.nativeElement.focus()
ps.: I would expect the FormControl api to expose a focus method, but this issue on gitHub suggests it may never happen.
For a more generic solution see
Is it possible to get native element for formControl? `
@Directive({
selector: '[ngModel]',
})
export class NativeElementInjectorDirective {
constructor(private el: ElementRef, private control : NgControl) {
(<any>control.control).nativeElement = el.nativeElement;
}
}
`
This will add the nativeElement to EACH form control once you add the directive to your module.
UPDATE: a much simpler solution for this usecase To set focus on the first invalid element on a form create a directive like this:
import { Directive, HostListener, ElementRef} from '@angular/core';
@Directive({
selector: '[focusFirstInvalidField]'
})
export class FocusFirstInvalidFieldDirective {
constructor(private el: ElementRef) { }
@HostListener('submit')
onFormSubmit() {
const invalidElements = this.el.nativeElement.querySelectorAll('.ng-invalid');
if (invalidElements.length > 0) {
invalidElements[0].focus();
}
}
}
Then simply add it to your form element tag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With