Angular, Forms

Autofocus angular form on submit

Spread the love

This document has been updated to the latest version of Angular 11 and tested with Angular 10. Content may still apply to all versions of Angular 2+.

When working with the required entry in the form sometimes the user may miss the required field. When this happens, users may be confused as to what needs to be resolved in order to continue the form. With autofocus angular form on submit, we can assist the user with focusing on invalid initial input when submitting the form.

In this example form, we have two inputs. Each input has the required confirmation to verify that the user has entered the value.

div class="container-fluid">
  <form
    class="row g-3"
    [formGroup]="contactsForm"
    #reactiveForm="ngForm"
    (ngSubmit)="submitContactsForm()"
  >
    <div class="col-md-6">
      <label for="name" id="name" class="col-sm-2 col-form-label">Name</label>
      <input
        formControlName="name"
        class="form-control"
        type="text"
        name="name"
        id="name"
        placeholder="Enter Name"
      />
    </div>
    <div class="col-md-6">
      <label for="department" class="col-sm-2 col-form-label">Department</label>
      <input
        formControlName="department"
        type="text"
        name="department"
        id="department"
        class="form-control"
        placeholder="Enter Department"
      />
    </div>
    <div class="col-md-6">
      <label for="eMail" class="col-sm-2 col-form-label">Email</label>
      <input
        formControlName="email"
        type="email"
        name="email"
        id="email"
        class="form-control"
        placeholder="Enter email"
      />
    </div>

    <div class="col-12">
      <button class="btn btn-primary" type="submit">Submit</button>
    </div>
  </form>
</div

app.component.ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, NgForm } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  contactsForm: FormGroup;
  contact = {
    name: '',
    email: '',
    department: ''
  }
  constructor(private _fb: FormBuilder) {
    this.contactsForm = this._fb.group({
      id: [Number],
      name: [
        '',
        [
          Validators.required,
          Validators.pattern('^[a-zA-Z-,]+(s{0,1}[a-zA-Z-, ])*$')
        ]
      ],
      department: ['', [Validators.required]],
      email: [
        '',
        [
          Validators.required
          //Validators.pattern('[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\\.[a-z]{2,3}')
        ]
      ]
    });
  }

  get formControls() {
    return this.contactsForm.controls;
  }

  submitContactsForm() {
    if (this.contactsForm.invalid) {
      return;
    } else {
      console.log(this.contactsForm.value);
    }
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AutoFocusDirective } from './autofocus.directive';

@NgModule({
  imports:      [ BrowserModule, FormsModule,ReactiveFormsModule ],
  declarations: [ AppComponent, HelloComponent,AutoFocusDirective ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Our form uses the Angular Reactive Forms and FormBuilder service to create the concept of our form. Log in to focus on the invalid input start when the user submits, we will create a separate index. We will call this guide AutoFocusDirective. When this guide is included in our form it will listen to the submission event knowing when to focus on the invalid first input.

import { Directive, HostListener, ElementRef } from '@angular/core';

@Directive({
	selector: '[autofocusInvalidInput]'
})
export class AutoFocusDirective {
	constructor(private el: ElementRef) {}

	@HostListener('submit')
	onFormSubmit() {
		const invalidInputControl = this.el.nativeElement.querySelector(
			'.ng-invalid'
		);

		if (invalidInputControl) {
			invalidInputControl.focus();
		}
	}
}

To listen to the submission event in our form item, we can use the @HostListener decorator to call our route when we are fired. Once we have an event, we can check if there is an invalid input. An easy way to test invalid input is to check for invalid CSS options made in HTML by Angular.

Just to test our form template, we can install the ElementRef service which will provide HTML form template reference. With the template we can use this.el.nativeElement.querySelector (‘. By invalid’) to get a list of invalid input. If there are invalid items, then we can focus on the first in the list.

Once the guide is done, we need to make sure we put it in the form of the form we want to behave.

div class="container-fluid">
  <form
    class="row g-3"
    autofocusInvalidInput
    [formGroup]="contactsForm"
    #reactiveForm="ngForm"
    (ngSubmit)="submitContactsForm()"
  >
    <div class="col-md-6">
      <label for="name" id="name" class="col-sm-2 col-form-label">Name</label>
      <input
        formControlName="name"
        class="form-control"
        type="text"
        name="name"
        id="name"
        placeholder="Enter Name"
      />
    </div>
    <div class="col-md-6">
      <label for="department" class="col-sm-2 col-form-label">Department</label>
      <input
        formControlName="department"
        type="text"
        name="department"
        id="department"
        class="form-control"
        placeholder="Enter Department"
      />
    </div>
    <div class="col-md-6">
      <label for="eMail" class="col-sm-2 col-form-label">Email</label>
      <input
        formControlName="email"
        type="email"
        name="email"
        id="email"
        class="form-control"
        placeholder="Enter email"
      />
    </div>

    <div class="col-12">
      <button class="btn btn-primary" type="submit">Submit</button>
    </div>
  </form>

If you want this global automation behavior in all forms in your Angular program you can change the administrator selector from [autofocusInvalidInput] to create a Complete demo of performance below!

References

Thank you! Like our Facebook page for more updates.


Spread the love

About Chandra

Technology lover. Professionally Software Developer and write some Technical Blog to help newcomer.
View all posts by Chandra →

4 thoughts on “Autofocus angular form on submit

Leave a Reply

Your email address will not be published. Required fields are marked *