AngularDoubts
AngularDoubts

Reputation: 499

Autofocus on a custom element in angular 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.

Upvotes: 2

Views: 10809

Answers (2)

T. Shashwat
T. Shashwat

Reputation: 1165

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>

Upvotes: 0

Patryk Brejdak
Patryk Brejdak

Reputation: 1601

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

Upvotes: 1

Related Questions