Adding autofocus to elements in Angular

Shreevardhan
Docon
Published in
1 min readSep 6, 2018

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.

--

--