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
}```
CodePudding user response:
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 !