'Probem with the focus function in Angular

I hope you can help me, I just started as a programmer and I have a newbie problem, I have two inputs, I want to write a series of numbers in my first input (DO) and then automatically pass to the second input (communal code).

Inputs:

two input elements with floating labels and sample data

I understand that it is done with focus but I can't get good results. I look forward to your responses, thank you.



Solution 1:[1]

Let suppose You have two inputs next to each other in the same dom tree level:

html:

<input  (change)="onInput1ChangeEvent($event)" />
<input #secondInput  />

ts: //get input tag reference

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
@Component({
  selector: 'app-Component',
  templateUrl: './app-Component.html',
  styleUrls: ['./app-Component.scss'],
})
  @ViewChild('secondInput') secondInput!: ElementRef;
constructor(){}

  onInput1ChangeEvent(event: any){
let do = event.target.value;
//let suppose max length value to focus next input is 10 letters

    let maxVal=10;
    let doLength =0;
    if(!!do){
    doLength = do.length;
    let focusNextInput = doLength == maxVal
    if(focusNextInput){
    //focus next input
        this.secondInput.nativeElement.focus();
    }
    
    
    }
      }

After a long discussion with Mr Eliseo about the easiest and more clean code method to deal with html template directly and with less variables:

html:

<input #firstInput (input)="!!firstInput.value && firstInput.value.length==10 && secondInput.focus()">
<input #secondInput  />

And finally I have to say thank You to Mr Eliseo for improving this answer and guiding us to get the best method to fix this issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1