简体   繁体   中英

Set focus on Child component textbox from Parent component in Angular

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM