Skip to content

Instantly share code, notes, and snippets.

@denis23x
Last active November 6, 2021 23:13
Show Gist options
  • Select an option

  • Save denis23x/00c235f79741052b1435378d9568e360 to your computer and use it in GitHub Desktop.

Select an option

Save denis23x/00c235f79741052b1435378d9568e360 to your computer and use it in GitHub Desktop.
/** @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