Skip to content

Instantly share code, notes, and snippets.

@cbejensen
Last active December 11, 2019 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbejensen/1fa0be01f5e2999a516be217b4fe977b to your computer and use it in GitHub Desktop.
Save cbejensen/1fa0be01f5e2999a516be217b4fe977b to your computer and use it in GitHub Desktop.
Abstract Angular Focus Component - enables parent components to focus an element in the child component's template
import { OnInit, Input, ElementRef, AfterViewInit } from '@angular/core';
export abstract class FocusComponent implements OnInit, AfterViewInit {
/**
* The element that can be focused.
*/
protected elemToFocus: ElementRef;
/**
* Can be set on initialization or updated later on to focus an element.
*/
protected shouldFocus: boolean;
@Input() set focus(shouldFocus: boolean | '') {
// Enables this property to be used on a component without assigning a value, i.e. <my-comp focus></my-comp>
// https://github.com/angular/angular/issues/14761#issuecomment-555396888
this.shouldFocus = shouldFocus === '' || shouldFocus;
if (shouldFocus && this._ranAfterViewInit) {
this.focusElement();
}
}
/**
* Enables component to know when `afterViewInit` has run. We need to wait for this hook before attempting
* to focus.
*/
private _ranAfterViewInit = false;
constructor() {}
ngOnInit() {}
ngAfterViewInit(): void {
if (this.shouldFocus) {
this.focusElement();
}
this._ranAfterViewInit = true;
}
/**
* Focuses an element if it exists.
*/
focusElement = () => {
const input = this.elemToFocus && this.elemToFocus.nativeElement;
if (input) {
input.focus();
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment