Categories: Angular

Focus First Invalid Input With Angular Forms

Here, we will learn about how to focus first invalid input element in Angular. This is essential when we are doing the validations and submitting the form, so the user can know quickly which input is invalid.

Step 1:-

Create an Angular application using this command

ng new demo
cd demo

Step 2:-

Create a Component in your project using this component

ng generate directive focus-Invalid-Input

Add the following code in your focus-Invalid-Input directives

import { Directive, HostListener, ElementRef } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { FormGroup } from '@angular/forms';

@Directive({
  selector: '[focusInvalidInput]'
})
export class focusInvalidInputDirective {

  constructor(private el: ElementRef) { }

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

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

Step 3:-

Add following code to app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  form: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.form = this.formBuilder.group({
      first: ['', Validators.required],
      last: ['', Validators.required],
    });
  }

  submit() {
    if (this.form.valid) {
      console.log(this.form);
    }
  }

}

Step 4:-

Add following code to app.component.html

<h1>Focus first invalid input on submit</h1>

<form focusInvalidInput [formGroup]="form" (ngSubmit)="submit()" class="formClass">
  <label for="first">First Name</label>
  <input formControlName="first" id="first" />

  <label for="last">Last Name</label>
  <input formControlName="last" id="last" />

  <br/>
  <br/>
  <button>submit</button>
</form>

Add following code to app. component. scss

label {
  display: block;
}

input.ng-invalid:focus {
  outline-color: red;
}

.formClass{
    margin-left: 10px;
}

Step 5:-

npm start
krishna kukadiya

Jr. .Net Developer

Share
Published by
krishna kukadiya

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago