*There are a lot of similar questions but I have not found a true duplicate that answers my question Apologies if I missed something.
I have a page with several inputs/buttons (The same component repeated) and need to focus on the correct input upon button click.
I have tried variations of elementRef, nativeElement, focusing based on the ID... but I can only get it to focus on the first one in the DOM or specific ones...
<ng-template #myTemplate let-context="context">
<input #foo [id]="'myInput'+context.id" />
<button class="btn" [id]="'btnAction'+context.id (click)="focusOnInput()"></button>
</ng-template>
Which renders like this in the DOM:
<input #foo id="myInput1" />
<button class="btn" id="btnAction1></button>
<input #foo id="myInput2" />
<button class="btn" id="btnAction2></button>
<input #foo id="myInput3" />
<button class="btn" id="btnAction3></button>
This is what I've been trying:
@ViewChild("foo") focusOnThis: ElementRef;
focusOnInput(): void {
this.focusOnThis.nativeElement.focus();
}
Desired behavior: When clicking on the button, focus on the respective input. Currently, it only focuses on the first one, or whichever ID I specify...