Focus an <input> element

前端 未结 4 674
挽巷
挽巷 2020-12-19 01:35

I\'ve many input boxes in a div and I need to focus one of them programmatically.

How to do it?

It\'s something like:



        
4条回答
  •  旧巷少年郎
    2020-12-19 02:02

    My approach would be to rely on a Directive and its selector, to remove the necessity of iterating over an array, and to avoid the local variables (I don't like the idea of having too many of them on my view), as Mark mentioned.

    I'm assuming that the user always want only one and it's hardcoded, which is enough for the case the user asked about. Having a dynamic element to focus would defeat this approach.

    The directive

    @Directive({
      selector : 'input[type=text][name=txt3]'
    })
    class Input {
      constructor(public renderer: Renderer, public elementRef: ElementRef) {}
    
      focusMe() {
        this.renderer.invokeElementMethod(this.elementRef.nativeElement, 'focus', []);
      }
    }
    

    The component would be basically the same in each answer

    export class App {
      @ViewChild(Input) input: Input;
    
      selectSample() {
        this.input.focusMe();
      }
    }
    

    Here's the plnkr.

提交回复
热议问题