[Fixed] Set focus on Child component textbox from Parent component in Angular

Issue

I am trying to set focus on a child component textbox from Parent component in Angular.

Parent Component HTML:

<button (click)="setFocusOnChildComponentTextBox()">Button</button>
<child-component></child-component>

Child Component HTML:

<input type="text" id="txt" name="txt"></input>

Parent Component TS:

setFocusOnChildComponentTextBox() {
// write code to set focus on child-component "txt" textbox
}

The above is just a sample code I am trying to achieve.

Normally in Angular we can pass input properties to child component and have output methods. In this case, I need to call a method of child component from the parent component.

Solution

In child component lets say you have input

<input type="text" #myInput></input>

In child component typescript have

@ViewChild('myInput', {read:ElementRef}) myInput: ElementRef<HTMLInputElement>;

In parent component typescript have

@ViewChild(ChildComponent) comp: ChildComponent;

to focus use

this.comp.myInput.nativeElement.focus();

Leave a Reply

(*) Required, Your email will not be published