Created
August 18, 2018 16:24
-
-
Save svdamani/cdab5b86667bcbfff613de81a48f2691 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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