Angular - Focus on input with dynamic IDs on click

时光毁灭记忆、已成空白 提交于 2019-12-02 12:25:55

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();
}

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!