Line data Source code
1 : import 'dart:html';
2 :
3 : import 'package:angular2/angular2.dart';
4 :
5 : @Directive(selector: 'textarea[autogrow]')
6 : class AutogrowDirective implements AfterViewInit {
7 : final ElementRef _ref;
8 :
9 4 : AutogrowDirective(this._ref);
10 :
11 : // Box sizing style property is set to border-box, to make behaviour
12 : // consistent with different css resets etc.
13 : @HostBinding('style.box-sizing') get boxSizing => 'border-box';
14 :
15 : // Only allow horizontal resize, as vertical resize is done automatically.
16 : @HostBinding('style.resize') get resize => 'horizontal';
17 :
18 80 : TextAreaElement get textArea => _ref.nativeElement;
19 :
20 : ngAfterViewInit() {
21 : // resize the height when the textarea is initialized
22 4 : resizeHeight();
23 : }
24 :
25 : /// Resize the height of the textarea to match the current content.
26 : /// This method is automatically triggered with new input. You can also
27 : /// trigger this method with a custom event, e.g.:
28 : ///
29 : /// textarea.dispatchEvent(new CustomEvent('input'));
30 : ///
31 : @HostListener('input')
32 : void resizeHeight() {
33 : // shrinks the textarea when needed
34 24 : textArea.style.height = 'auto';
35 :
36 : // calculates the border top width + border bottom width
37 40 : final borderCorrection = textArea.offsetHeight - textArea.clientHeight;
38 :
39 : // let the height match the scrollHeight + a border correcion added
40 : // note that this will work only because we force the textarea to have
41 : // box-sizing: border-box
42 56 : textArea.style.height = '${textArea.scrollHeight + borderCorrection}px';
43 : }
44 : }
|