Last active
November 6, 2021 23:13
-
-
Save denis23x/00c235f79741052b1435378d9568e360 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /** @format */ | |
| import { Directive, ElementRef, OnInit, OnDestroy, Input } from '@angular/core'; | |
| import { fromEvent, Observable, Subscription } from 'rxjs'; | |
| @Directive({ | |
| selector: '[appTextarea]' | |
| }) | |
| export class AppTextareaDirective implements OnInit, OnDestroy { | |
| @Input() | |
| set appAutofocus(autofocus: boolean) { | |
| this.autofocus = autofocus; | |
| } | |
| resize$: Subscription; | |
| autofocus: boolean; | |
| input: Observable<Event>; | |
| focus: Observable<Event>; | |
| constructor(private el: ElementRef) {} | |
| ngOnInit() { | |
| this.resize$ = fromEvent(this.el.nativeElement, 'input').subscribe(() => this.onAutosize()); | |
| const timeout = setTimeout(() => { | |
| this.onAutosize(); | |
| if (this.autofocus) { | |
| this.el.nativeElement.focus(); | |
| } | |
| clearTimeout(timeout); | |
| }, 50); | |
| } | |
| onAutosize() { | |
| this.el.nativeElement.style.height = 'auto'; | |
| this.el.nativeElement.style.height = this.el.nativeElement.scrollHeight - 32 + 'px'; | |
| } | |
| ngOnDestroy() { | |
| this.resize$.unsubscribe(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment