Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set focus in input element after submit and reset form

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>
like image 674
miguelferdis Avatar asked Mar 29 '17 18:03

miguelferdis


People also ask

How do you set the input element to focus?

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.

How do you reset input value after submitting?

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.

Which attribute can be used to set focus to an input element?

The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.

How do you reset input field in form?

To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.


2 Answers

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.

like image 133
rafaelbiten Avatar answered Oct 23 '22 05:10

rafaelbiten


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

like image 41
Remco Vlierman Avatar answered Oct 23 '22 04:10

Remco Vlierman