-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtextarea-autosize.directive.ts
More file actions
52 lines (44 loc) · 1.79 KB
/
textarea-autosize.directive.ts
File metadata and controls
52 lines (44 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { afterNextRender, Directive, ElementRef, inject, input } from '@angular/core'
import { FormControlDirective } from '@angular/forms'
import { Logger } from '@shiftcode/logger'
import { LoggerService, onDestroy, ResizeService } from '@shiftcode/ngx-core'
import { takeUntil } from 'rxjs'
/**
* Standalone AutosizeDirective for TextArea
* ONLY works with Reactive Forms (necessary to use FormControlDirective)
*/
@Directive({
selector: 'textarea[scAutosize]',
standalone: true,
host: {
'[style.resize]': '"none"',
'[style.overflow]': '"hidden"',
'[rows]': 'rows()',
},
})
export class TextareaAutosizeDirective {
readonly rows = input<number | string>(1)
readonly element: HTMLTextAreaElement = inject(ElementRef).nativeElement
private readonly formControlDir = inject(FormControlDirective)
private readonly logger: Logger = inject(LoggerService).getInstance('TextareaAutosizeDirective')
private readonly onDestroy$ = onDestroy()
constructor() {
afterNextRender(() => {
this.resize()
if (this.formControlDir.control) {
this.formControlDir.control.valueChanges.pipe(takeUntil(this.onDestroy$)).subscribe(this.resize.bind(this))
} else {
this.logger.error('FormControl not set yet on FormControlDirective - but necessary')
}
})
inject(ResizeService).observe(this.element).pipe(takeUntil(this.onDestroy$)).subscribe(this.resize.bind(this))
}
resize(): void {
// Calculate border height which is not included in scrollHeight
const borderHeight = this.element.offsetHeight - this.element.clientHeight
// Reset textarea height to auto that correctly calculate the new height
this.element.style.height = 'auto'
// Set new height
this.element.style.height = `${this.element.scrollHeight + borderHeight}px`
}
}