Search code examples
angularfocus

To focus on a component containing an input


I have a my-input component from the library. It's just a wrapper for input. How can I do the focus if I press span?

<div>
 <span (click)="onClickHandler();></span>
 <my-input #myinput></my-input>
</div>

this.myinput.nativeElement.focus() doesn't work


Solution

  • First pass read argument to ViewChild to get component ElementRef

     @ViewChild('myinput',{read:ElementRef}) myInput:ElementRef;
    

    Then use querySelector on nativeElement to access the input element which is inside the my-input component

    onClickHandler(){
        this.myInput.nativeElement.querySelector('input').focus();
      }
    

    Working Example