角度-专注于点击时具有动态ID的输入 [英] Angular - Focus on input with dynamic IDs on click

查看:117
本文介绍了角度-专注于点击时具有动态ID的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

*有很多类似的问题,但是我没有找到一个真正的副本来回答我的问题,如果我错过了一些东西,抱歉.

*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.

我尝试了elementRef,nativeElement的变体,重点是基于ID ...但是我只能让它专注于DOM中的第一个或特定的对象...

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>

哪个在DOM中呈现如下:

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>

这是我一直在尝试的:

@ViewChild("foo") focusOnThis: ElementRef;
focusOnInput(): void {
this.focusOnThis.nativeElement.focus();
}

所需行为: 单击按钮时,将焦点放在相应的输入上. 目前,它仅关注第一个或我指定的ID ...

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...

推荐答案

您可以在按钮单击处理程序中调用foo.focus().由于模板引用变量#foo的范围是模板实例,因此它将引用同级输入元素.

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>

请参见此stackblitz 演示.

如果需要通过方法设置焦点,请将foo作为参数传递给它:

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

这篇关于角度-专注于点击时具有动态ID的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆