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.

2
  • Does this answer your question? how to focus on an input in Angular Commented Apr 22, 2021 at 17:31
  • Thanks Richard. It partially answers the question but I want to know how to access the child component from parent component. Commented Apr 23, 2021 at 9:21

1 Answer 1

6

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();
Sign up to request clarification or add additional context in comments.

2 Comments

I have a similar situation but I am using the <child-component> twice in my template and am getting the error "Found 2 elements with non-unique id ". any suggestions on how to resolve?
use viewchildren to get both inputs in array, if want them separately, give a different name like #myInputTwo

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.