Autofocus on a custom element in angular 2

Viewed 9081

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 Answers

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();
   }
}

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>

Related