Home > OS >  To focus on a component containing an input
To focus on a component containing an input

Time:10-05

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

CodePudding user response:

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

  • Related