Dylan Smyth
Dylan Smyth

Reputation: 162

How to set focus on next <input> within *ngFor directive

I have a form that captures a number of barcodes based on the number of pallets the user has desired to enter. This, in turn, repeats a set of inputs, each capturing a unique barcode.

barcodes.component.html

<div *ngFor="let i of components(number).fill(1), let x = index">
    <input class="form-control" type="text" 
        [(ngModel)]="barcode[x]" (keyup.enter)="keytab($event)"> 
</div>

barcodes.component.ts

keytab(e) {
    let element = e.srcElement.nextElementSibling; // get the sibling element
    
    if(element == null)  // check if its null
        return;
    else
        element.focus();   // focus if not null
}

By default, the scanner automatically executes a keyup.enter event after it has scanned a valid barcode.

I would like the focus to be shifted from the input that has just been scanned, to the next available sibling that is empty.

TL;DR How do I set focus to next available input sibling that has not yet been populated?

Upvotes: 0

Views: 769

Answers (2)

Dylan Smyth
Dylan Smyth

Reputation: 162

I managed to solve this issue with plain old Javascript

On my element inside *ngFor* I add a data attribute as

[attr.id]="x"

Based on the index value of the *ngFor.

In my keytab method I do the following

if (event.which === 13) {
    var target = event.target || event.srcElement || event.currentTarget;
    var id = target.attributes.id; // returns target element object
    var val = id.nodeValue; // gets node value of element
            
    if((+val + 1) < this.number) { //prevents focus to 'null' element
        document.getElementById(String(+val + 1)).focus(); //shifts focus to next element
    }
}

Upvotes: 1

micronyks
micronyks

Reputation: 55443

You can do following changes,

(keyup.enter)="keytab($event.target)"


keytab(e) {
    let element = e.parentElement.parentElement.childNodes; // get the parent element
    
    for(let child of element){
       if(child.firstChild.type === "text" && child.firstChild.innerHTML === ""){
           child.firstChild.focus();
            return;
        }
    }

Upvotes: 1

Related Questions