Dealing with focus is something I have had to do in nearly every Angular project I’ve worked on. There are a few directives out there to accomplish this but none that allowed event-driven focus and were safe for server-side rendering. I’m happy to announce angular-input-focus on the NPM. To get started, install the library in your project:

npm install angular-input-focus --save

Next, add it to your list of imports:

import { AngularInputFocusModule } from 'angular-input-focus';

@NgModule({
  imports: [AngularInputFocusModule]
})

For autofocus-like functionality, you can set libFocus to true (or a condition):

<!-- Focus First name when control is rendered -->
First name: <input type="text" name="fname" [libFocus]="true">
Last name: <input type="text" name="lname">

You can also pass an EventEmitter<boolean> to the setFocus input. Imagine a component called MyComponent:

export class MyComponent {
    // We will pass this to the directive in our view
    focusEvent = new EventEmitter<boolean>();
    // When called, will set the focus on our input
    setFocus() {
        this.focusEvent.emit(true);
    }
}

And the template for MyComponent:

<input [libFocus]="false" [setFocus]="focusEvent">`

Whenever your focusEvent emits a value, your element will focus/blur depending on whether the emitted value is true or false.

Project Status

I have tested this directive in most major browsers / OSes. I have also been using similar code in production apps for years. As of the time of this writing, I have 100% code coverage and up-to-date dependencies:

NPM Build Status Test Status Code Coverage Dependencies Status License

What’s Next?

Head over to the project page on GitHub. Do you run in to a bug? Have ideas for improvement? Want to collaborate? Submit an issue!