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';

  selector: '[focusInvalidInput]'
export class focusInvalidInputDirective {

  constructor(private el: ElementRef) { }

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

    if (invalidControl) {

Step 3:-

Add following code to app.component.ts

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

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

  form: FormGroup;

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

  submit() {
    if (this.form.valid) {


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" />


Add following code to app. component. scss

label {
  display: block;
} {
  outline-color: red;

    margin-left: 10px;

Step 5:-

npm start

Submit a Comment

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


Select Categories