angulartemplate-variables

Angular 4 template variable focus


I have this cell template that shows the value of an Object into a span element, or, if the row is being editing, shows the value inside an input.

<ng-template ngx-datatable-cell-template let-rowIndex="rowIndex" let-row="row" let-value="value">
    <span
        *ngIf="!editing[rowIndex]">
        {{value}}
    </span>
    <input
        #myInput
        autofocus
        (blur)="setValue($event, value , row)"
        *ngIf="editing[rowIndex]"
        type="text"
        [value]="value"
    />
</ng-template>

When I click my edit button, I need to focus and select the text. No problem with that. I have

@ViewChild('myInput') myInput;

and

private focusInput(){       
    this.myInput.nativeElement.focus();
    this.myInput.nativeElement.select();
}

The problem is if I need to edit "simultaneously" 2 rows, after clicking the 1st-row edit button, is selected and focused, but when I click the 2nd row's edit button, the 1st input gets the focus again. I think is angular finding the first #myinput element available and focusing them, because, if I click the row number 5 in the first place, it focuses correctly and when any of the previous rows are marked for edit, the behavior is fine.

How can I make this work for each row even when other #myinput are present in the template?


Solution

  • If you only have 2 inputs in total, I would call the first one #myInput1 and the second #myInput2 and then have two @ViewChilds. Its not clear what calls focusInput, but as @joseph-webber mentioned, you should then pass an index to that call, eg :

    private focusInput(index){
        this['myInput' + index].nativeElement.focus();
        this['myInput' + index].nativeElement.select();
    }
    

    if you have many inputs, this approach may get messy, so you may need to use ViewChildren instead of ViewChild