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