0
votes

I have my 6 inputs beside each other in one row like this

component.html <li *ngFor="let i of [1,2,3,4,5,6]"> <input class="form-control" placeholder="0" type="text" maxlength="1" (keyup)="onDigitInput($event)">

Now i tried this in my controller to focus next input element when maximum length limit reaches automatically.

onDigitInput(event: any) {
  let element;
  if (event.code !== 'Backspace')

  element = event.srcElement.nextElementSibling;
  console.log('Element : ',event.srcElement)

  if (event.code === 'Backspace')
    element = event.srcElement.previousElementSibling;

  if (element == null)
    return;
  else
    element.focus();
}

But the problem with my solution is that it will only work if all input elements must be beside each other without wrapping/nesting in further element. But in my case my each input element is wrapped in <li> tag so that's why it's not working. So can any one suggest any solution to for this problem via any function or even directive if possible.

1

1 Answers

0
votes

I adapted the solution you posted to accomodate the structure that you have (inputs inside lis).

  onDigitInput(event: any) {
    const element = this.getNextInput(
      event.srcElement,
      event.code === "Backspace"
    );

    if (!element) {
      return;
    }

    element.focus();
  }

  getNextInput(currentInput: Element, isBackspace: boolean): HTMLElement {
    if (!currentInput) {
      return null;
    }
    const parentListItem = currentInput.parentElement;
    let nextListItem = isBackspace
      ? parentListItem.previousElementSibling
      : parentListItem.nextElementSibling;
    return nextListItem?.firstChild as HTMLElement;
  }