0

KeyboardEvent.srcElement is now deprecated (according to my IntelliJ) and TypeScript now uses KeyboardEvent.target.

My question is: With .target, how do you access the .nextElementSibling field that .srcElement used to have? I am trying to implement the code below to focus on the next input field of an HTML form when the Enter key is pressed.

keytab(event){
    let element = event.srcElement.nextElementSibling; // get the sibling element

    if(element == null)  // check if its null
        return;
    else
        element.focus();   // focus if not null
}```

1 Answers1

1

One Way to solve this problem is dynamically assign an id to your input fields in the form based on the number of input fields.

Then attach a keyup trigger for your desired function like

<form [formGroup]="myForm">
    <div formArrayName="things">
        <div *ngFor="let thing of things.controls; let i=index">
            <label [for]="'input' + i">Thing {{i}}:</label>
            <input type="text" [formControlName]="i" [name]="'input' + i" [id]="'input' + i" (keyup.enter)="focusNext(i)"  />
        </div>
    </div>
</form>

once you have added a dynamic id to each of the form fields and you have defined a relevant function for the manipulation you want to perform which might look like this

 public focusNext(i) {
        let nextElementSiblingId = 'input'+ i+1;
        if (i<this.things.controls.length) {
         document.querySelector(`#${nextElementSiblingId}`).focus()
        }     
      
  }

Hope it solves your problem !

  • 1
    Thanks for your help, Shubham! This wasn't exactly the solution I used, but some parts of your code were crucial to solving the issue I was facing! – Thomas Michael Plantin May 13 '22 at 04:05
  • Using a directive: https://stackoverflow.com/questions/53690973/change-behaviour-of-enter-key-in-a-phone-angular-5/53691367#53691367 – Eliseo May 13 '22 at 07:10