Last active
August 17, 2021 21:06
-
-
Save touhidrahman/c5dfb10c530397cd94b5143bbeb0987b to your computer and use it in GitHub Desktop.
autosize-textarea.directive.ts
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
| 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