Newer
Older
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
import {
AfterViewInit, Directive, ElementRef, EventEmitter, HostListener, Input, OnChanges, Output, SimpleChanges
} from '@angular/core';
@Directive({
selector: '[dynamicRows]'
})
export class DynamicRowsDirective implements AfterViewInit, OnChanges {
@Input() fontSize!: number;
@Input() expectedCharactersCount!: number;
@Output() dynamicRowsChange: EventEmitter<number> = new EventEmitter<number>();
@HostListener('window:resize') onResize() {
// guard against resize before view is rendered
this.calculateDynamicRows();
}
constructor(public elementRef: ElementRef) {}
ngAfterViewInit(): void {
this.calculateDynamicRows();
}
calculateDynamicRows(): void {
// give the textarea time to render before calculating the dynamic row count
setTimeout(() => {
const averageCharWidth = this.fontSize / 2;
if (this.elementRef.nativeElement.offsetWidth) {
this.dynamicRowsChange.emit(
Math.ceil((
this.expectedCharactersCount * averageCharWidth) /
this.elementRef.nativeElement.offsetWidth
)
);
}
});
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.fontSize || changes.expectedCharactersCount) {
this.calculateDynamicRows();
}
}
}