@@ -2,9 +2,12 @@ import {
2
2
AfterViewInit ,
3
3
Directive ,
4
4
ElementRef ,
5
- HostListener ,
6
5
Input ,
6
+ OnDestroy ,
7
7
} from '@angular/core' ;
8
+ import { NgControl } from '@angular/forms' ;
9
+ import { Subject } from 'rxjs' ;
10
+ import { startWith , takeUntil } from 'rxjs/operators' ;
8
11
9
12
import { calcTextareaHeight } from './utils' ;
10
13
@@ -22,23 +25,15 @@ export interface AutoSizeValue {
22
25
* Directive to automatically resize a textarea to fit its content.
23
26
*/
24
27
@Directive ( {
25
- // tslint:disable-next-line: directive-selector
26
- selector : 'textarea[autosize]' ,
28
+ selector :
29
+ // tslint:disable-next-line: directive-selector
30
+ 'textarea[autosize][ngModel],textarea[autosize][formControl],textarea[autosize][formControlName]' ,
27
31
exportAs : 'TextareaAutosize' ,
28
32
} )
29
- export class AutosizeDirective implements AfterViewInit {
33
+ export class AutosizeDirective implements AfterViewInit , OnDestroy {
30
34
private _autoSize : AutoSizeValue = DEFAULT_VALUE ;
31
35
32
- private textareaCalcStyle : {
33
- minHeight ?: string ;
34
- maxHeight ?: string ;
35
- height ?: string ;
36
- } = { } ;
37
-
38
- @HostListener ( 'input' )
39
- onTextareaInput ( ) {
40
- this . resizeTextarea ( ) ;
41
- }
36
+ private readonly destroy$$ = new Subject < void > ( ) ;
42
37
43
38
@Input ( 'autosize' )
44
39
get autoSize ( ) {
@@ -53,21 +48,32 @@ export class AutosizeDirective implements AfterViewInit {
53
48
this . resizeTextarea ( ) ;
54
49
}
55
50
56
- constructor ( protected elementRef : ElementRef < HTMLTextAreaElement > ) { }
51
+ constructor (
52
+ private readonly elRef : ElementRef < HTMLTextAreaElement > ,
53
+ private readonly ngControl : NgControl ,
54
+ ) { }
57
55
58
56
resizeTextarea ( ) {
57
+ const el = this . elRef . nativeElement ;
59
58
const autoSize = this . _autoSize ;
60
- this . textareaCalcStyle = calcTextareaHeight (
61
- this . elementRef . nativeElement ,
62
- autoSize . minRows ,
63
- autoSize . maxRows ,
59
+ Object . assign (
60
+ el . style ,
61
+ calcTextareaHeight (
62
+ el ,
63
+ autoSize . minRows ?? DEFAULT_VALUE . minRows ,
64
+ autoSize . maxRows || DEFAULT_VALUE . maxRows , // 0 is unacceptable
65
+ ) ,
64
66
) ;
65
- this . elementRef . nativeElement . style . minHeight = this . textareaCalcStyle . minHeight ;
66
- this . elementRef . nativeElement . style . maxHeight = this . textareaCalcStyle . maxHeight ;
67
- this . elementRef . nativeElement . style . height = this . textareaCalcStyle . height ;
68
67
}
69
68
70
69
ngAfterViewInit ( ) {
71
- this . resizeTextarea ( ) ;
70
+ this . ngControl . valueChanges
71
+ . pipe ( startWith ( null as void ) , takeUntil ( this . destroy$$ ) )
72
+ . subscribe ( ( ) => this . resizeTextarea ( ) ) ;
73
+ }
74
+
75
+ ngOnDestroy ( ) {
76
+ this . destroy$$ . next ( ) ;
77
+ this . destroy$$ . complete ( ) ;
72
78
}
73
79
}
0 commit comments