Adding autofocus to elements in Angular

Shreevardhan
Sep 6, 2018 · 1 min read

autofocus is an HTML5 attribute that doesn’t work consistently across different browsers when a (form) element is inserted dynamically into the DOM after the initial page load. Thanks to Angular’s attribute directives, we can make the existing attribute work correctly within components in a SPA. Here is an implementation:

Points to note:

  1. This implementation doesn’t support dynamic attribute binding. In case element focus has to be controlled by properties, lifecycle hooks should be changed from ngOnInit to ngOnChanges.
  2. setTimeout with 0 second timeout is added to prevent the annoying ExpressionChangedAfterItHasBeenCheckedError.

Docon

At Docon, we strive to enable a connected healthcare ecosystem for better patient outcomes by building doctor workflow management to drive efficiency, better decision making & patient convenience.

Shreevardhan

Written by

Full Stack Developer

Docon

Docon

At Docon, we strive to enable a connected healthcare ecosystem for better patient outcomes by building doctor workflow management to drive efficiency, better decision making & patient convenience.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade