2

I have an html page with html elements and my own custom component(which is a dropdown) created in angular 2. as:

<div>
<input type="text" name="fname"><br>
<myDropdownComp autofocus> </myDropdownComp>
</div>

On pageload, focus should be on my custom dropdown component. How can I do that? I tried giving 'autofocus' which is not working. Please help. Thanks in advance.

2
  • Inside your myDropdownComp you will need to write the custom logic in ngOnInit for element focus. Commented Sep 21, 2018 at 5:47
  • in this case autofocus only works when page is loaded. When we press the button next time, browser does not respect autofocus value as page is already solution. Commented Sep 21, 2018 at 5:57

2 Answers 2

1

Firstly, element is need to be focusable, to achieve this you have to set tabIndex attribute to element.

<myDropdownComp tabIndex="-1"></myDropDownComp> // now component is focusable

Now you can try with autofocus attribute, but it would be preferred to do this in ngAfterViewInit, to check if there is already focused element, if there is one, blur it, and focus this element.

export class MyDropdownComponent implements AfterViewInit {
   constructor(element: ElementRef) { }

   ngAfterViewInit() {
      if (document.activeElement) {
         document.activeElement.blur();
      }
      this.element.nativeElement.focus();
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

run npm install angular-autofocus-fix --save in cli

import import { AutofocusModule } from 'angular-autofocus-fix'; in your module and AutofocusModule in import section.

then you can freely use autofocus as an attribute in any tag.

or

use autofocus="true" in input tag, see updated snippet

<div>
<input autofocus="true" type="text" name="fname"><br>
<myDropdownComp > </myDropdownComp>
</div>

Comments

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.