Angular - Focus on input with dynamic IDs on click

后端 未结 2 1125
心在旅途
心在旅途 2021-01-28 13:45

*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

相关标签:
2条回答
  • 2021-01-28 13:58

    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();
    }
    
    0 讨论(0)
  • 2021-01-28 14:11

    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();
    }
    
    0 讨论(0)
提交回复
热议问题