Skip to content

Instantly share code, notes, and snippets.

@touhidrahman
Last active August 17, 2021 21:06
Show Gist options
  • Select an option

  • Save touhidrahman/c5dfb10c530397cd94b5143bbeb0987b to your computer and use it in GitHub Desktop.

Select an option

Save touhidrahman/c5dfb10c530397cd94b5143bbeb0987b to your computer and use it in GitHub Desktop.
autosize-textarea.directive.ts
import { Directive, ElementRef, HostListener, Input } from "@angular/core";
@Directive({
selector: "[appTextareaAutosize]"
})
export class TextareaAutosizeDirective {
@Input() minRows = 2;
@Input() maxRows = 4;
private offsetHeight = 0;
private readonly avgLineHeight = 20;
@HostListener("input")
onInput(): void {
const element: HTMLTextAreaElement = this.element.nativeElement;
if (this.offsetHeight <= 0) {
this.offsetHeight = element.scrollHeight;
}
element.rows = this.minRows;
const rows = Math.floor(
(element.scrollHeight - this.offsetHeight) / this.avgLineHeight
);
const rowsCount = this.minRows + rows;
element.rows = rowsCount > this.maxRows ? this.maxRows : rowsCount;
}
constructor(private element: ElementRef) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment