简体   繁体   中英

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:

两个带有浮动标签和示例数据的输入元素

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM