Skip to main content

Angular Reactive Forms: Move Focus to Next Input on Enter Key Press

  • In Reactive Form Multiple input filed help of enter key go next 1 by 1
  • function is trying to move focus to the next input field when the Enter key is pressed.

• If you have multiple inputs, this will always focus only on one specific input.

• Instead, dynamically focus on the next input.


• Hardcoded ID (#eName input)

• If you have multiple inputs, this will always focus only on one specific input.

• Instead, dynamically focus on the next input.

• Using setTimeout(100)

• This is useful if the UI needs time to update, but it's better to check if it's necessary.

• Using querySelector globally

• This works, but ViewChild in Angular is a better alternative for accessing elements.

Test.ts

  focusoutgrp() {

    // Get all input fields in the form

    const inputs: NodeListOf<HTMLInputElement> = document.querySelectorAll('input');

    // Find the currently focused input

    const activeElement = document.activeElement as HTMLInputElement;

    const currentIndex = Array.from(inputs).indexOf(activeElement);

    // Move focus to the next input field if available

    if (currentIndex !== -1 && currentIndex < inputs.length - 1) {

      setTimeout(() => {

        inputs[currentIndex + 1].focus();

      }, 100);

    }

  }

Test.html

<form>

   <lable>Name</lable>

   <input type="text"  (keydown.enter)="focusoutgrp()"/>


   <lable>Email</lable>

   <input type="text"  (keydown.enter)="focusoutgrp()"/>


   <lable>password</lable>

   <input type="text" (keydown.enter)="focusoutgrp()" />

</form>

How it is work ?

1.  When the user presses Enter, focusoutgrp() is triggered.

2. It finds the current input and moves to the next.

3. If it's the last input, focus remains (or you can trigger form submission).




 

Comments

© 2020 The JavaDS Hub

Designed by Open Themes & Nahuatl.mx.