Skip to content

Instantly share code, notes, and snippets.

@svdamani
Created August 18, 2018 16:24
Show Gist options
  • Save svdamani/cdab5b86667bcbfff613de81a48f2691 to your computer and use it in GitHub Desktop.
Save svdamani/cdab5b86667bcbfff613de81a48f2691 to your computer and use it in GitHub Desktop.
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { DOCUMENT } from '@angular/common';
import { Directive, ElementRef, Inject, Input, OnInit } from '@angular/core';
@Directive({ selector: '[myAutoFocus], [autofocus]' })
export class AutoFocusDirective implements OnInit {
private host: HTMLElement;
private focused: Element;
private autoFocus = true;
@Input()
set autofocus(value: boolean) {
this.autoFocus = coerceBooleanProperty(value);
}
constructor(private elRef: ElementRef, @Inject(DOCUMENT) private document: HTMLDocument) {
this.host = elRef.nativeElement;
this.focused = document.activeElement;
}
ngOnInit(): void {
if (this.autoFocus && this.host && this.host !== this.focused) {
setTimeout(() => this.host.focus());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment