3

In angular 4, I have a component nested inside of another. The inner or the child component contains: a button, an input and a drop down list.
On the parent page, when I click on the button, both the input and the drop-down are displayed.

What is a good way to set focus of the input when clicking the button?

What I tried so far:
In the child component, I added an id on the input: <input #inputId ... >, then in the same method triggered when the button is pressed, in the child component, I added:

$('#inputId').focus();

But this has no effect...
Any suggestions?

1 Answer 1

2

The notation #inputId isn't something you can search for using a jQuery selector. What that notation gives you is something you can access from the parent component with a declaration like this:

  @ViewChild('inputId') myInput: ElementRef;

Once you have this element reference, then you'd grab focus with:

(myInput.nativeElement as HTMLInputElement).focus();

In some situations, you might need:

setTimeout(() => {
  (myInput.nativeElement as HTMLInputElement).focus();
});
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you kshetline, I added the grab focus part in the child component, no effect yet (it's in the method triggered when I click the button). should I have placed it in the parent instead?
It's kind of hard to comment without seeing more of the code. The @ViewChild declaration has to be in whatever code has #inputId declared in its template. If myInput is defined, then you've got it in the right place. Then your event handler should be in the same class too, in order to see myInput. Were you getting any console errors, or just no result at all?
I added above the suggestion that you might want to use setTimeout before requesting focus.
Wow. It worked with the setTimeout!! But why? I would never have figured it out. Thank you kshetline!
Your event handler might not be the only event handler responding to the click event. Another event handler for that click might in fact request focus for the element that was clicked on, and if it does that after your focus request on the input field, the last such request will get priority. Using setTimeout ensures that the focus request for the input field happens last.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.