Adding autofocus to elements in Angular
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:
- This implementation doesn’t support dynamic attribute binding. In case element focus has to be controlled by properties, lifecycle hooks should be changed from
ngOnInittongOnChanges. setTimeoutwith 0 second timeout is added to prevent the annoyingExpressionChangedAfterItHasBeenCheckedError.

