【问题标题】:Angular - Focus on input with dynamic IDs on clickAngular - 专注于点击时具有动态 ID 的输入
【发布时间】:2019-04-18 14:08:54
【问题描述】:

*有很多类似的问题,但我没有找到一个真正的副本来回答我的问题,如果我错过了什么,请致歉。

我有一个包含多个输入/按钮的页面(重复相同的组件),并且需要在按钮单击时关注正确的输入。

我尝试了 elementRef、nativeElement、基于 ID 的变体……但我只能让它专注于 DOM 中的第一个或特定的……

<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 中呈现如下:

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

【问题讨论】:

    标签: angular input focus closest elementref


    【解决方案1】:

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

    <ng-template #myTemplate let-context="context">
      <input #foo />
      <button class="btn" (click)="foo.focus()"></button>
    </ng-template>
    

    请参阅this stackblitz 以获取演示。


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

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

    【讨论】:

    • 感谢您的回复。这看起来干净简单,但不幸的是它在我的项目中不起作用。还有其他事件需要首先触发才能使输入可见,所以我猜这会导致问题。最好我会从 ts 文件中的函数设置焦点,以便我可以先运行 otehr 的东西....
    • 顺便说一句,使用问题中给出的模板,当按钮可见时,输入元素是可见的。如果发生其他事情导致输入不可见,请在问题中包含相关代码/标记,或进行堆栈闪电战以显示问题。
    【解决方案2】:

    如何使用带有 id 的数据属性并从中获取输入?

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

    【讨论】:

    • 这是一个聪明的主意 - 不幸的是,我收到一个错误,它无法绑定到“组”,因为它不是按钮的已知属性......不知道为什么......
    • 啊。对不起。没有测试它。刚刚更新了模板。这是因为常规按钮没有该属性。但是你可以使用attr. 告诉 Angular,你只想设置 html 属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 2022-10-16
    • 1970-01-01
    • 2018-09-30
    • 2013-09-23
    • 1970-01-01
    相关资源
    最近更新 更多