Reputation: 1397
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?
Upvotes: 3
Views: 9283
Reputation: 13682
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();
});
Upvotes: 2