*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
How about to use a data-attribute with id and get the input from it?
<ng-template #myTemplate let-context="context">
<input [attr.data-group]="context.id" />
<button class="btn" [attr.data-group]="context.id" (click)="focusOnInput($event)"></button>
</ng-template>
<input data-group="1" />
<button class="btn" data-group="1"></button>
<input data-group="2" />
<button class="btn" data-group="2"></button>
<input data-group="3" />
<button class="btn" data-group="3"></button>
// component constructor
constructor(
private readonly elementRef: ElementRef,
// ...
) {
// ...
}
focusOnInput(event: MouseEvent): void {
const groupId = (<HTMLElement>event.target).dataset.group;
const input = this.elementRef.nativeElement.querySelector(`input[data-group="${groupId}"]`);
input.focus();
}
You can call foo.focus()
in the button click handler. Since the scope of the template reference variable #foo
is the template instance, it will refer to the sibling input element.
<ng-template #myTemplate let-context="context">
<input #foo />
<button class="btn" (click)="foo.focus()"></button>
</ng-template>
See this stackblitz for a demo.
If you need to set the focus from a method, pass foo
to it as an argument:
<ng-template #myTemplate let-context="context">
<input #foo />
<button class="btn" (click)="focusOnInput(foo)"></button>
</ng-template>
focusOnInput(input): void {
// Do something else here
...
input.focus();
}