2

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.

developer
  • 1,401
  • 4
  • 28
  • 73
  • Does this answer your question? [how to focus on an input in Angular](https://stackoverflow.com/questions/49927624/how-to-focus-on-an-input-in-angular) – R. Richards Apr 22 '21 at 17:31
  • Thanks Richard. It partially answers the question but I want to know how to access the child component from parent component. – developer Apr 23 '21 at 09:21

1 Answers1

3

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();
Aakash Garg
  • 10,649
  • 2
  • 7
  • 25
  • I have a similar situation but I am using the twice in my template and am getting the error "Found 2 elements with non-unique id ". any suggestions on how to resolve? – T Esh Jan 20 '22 at 04:24
  • use viewchildren to get both inputs in array, if want them separately, give a different name like #myInputTwo – Aakash Garg Jan 20 '22 at 08:22