Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. import {AfterViewInit, Directive, HostListener, Input, ElementRef} from '@angular/core';
  2.  
  3. @Directive({
  4. selector: '[Autosize]'
  5. })
  6. export class AutosizeDirective implements AfterViewInit {
  7.  
  8. private el: HTMLElement;
  9. private _minHeight: string;
  10. private _maxHeight: string;
  11. private _lastHeight: number;
  12. private _clientWidth: number;
  13.  
  14. @Input('minHeight')
  15. get minHeight() {
  16. return this._minHeight;
  17. }
  18. set minHeight(val: string) {
  19. this._minHeight = val;
  20. this.updateMinHeight();
  21. }
  22.  
  23. @Input('maxHeight')
  24. get maxHeight() {
  25. return this._maxHeight;
  26. }
  27. set maxHeight(val: string) {
  28. this._maxHeight = val;
  29. this.updateMaxHeight();
  30. }
  31.  
  32. @HostListener('window:resize', ['$event.target'])
  33. onResize(textArea: HTMLTextAreaElement) {
  34. //Only apply adjustment if element width had changed.
  35. if (this.el.clientWidth === this._clientWidth) return;
  36. this._clientWidth = this.element.nativeElement.clientWidth;
  37. this.adjust();
  38. }
  39.  
  40. @HostListener('input',['$event.target'])
  41. onInput(textArea: HTMLTextAreaElement): void {
  42. this.adjust();
  43. }
  44.  
  45. constructor(public element: ElementRef){
  46. this.el = element.nativeElement;
  47. this._clientWidth = this.el.clientWidth;
  48. }
  49.  
  50. ngAfterViewInit(): void{
  51. // set element resize allowed manually by user
  52. const style = window.getComputedStyle(this.el, null);
  53. if (style.resize === 'both') {
  54. this.el.style.resize = 'horizontal';
  55. }
  56. else if (style.resize === 'vertical') {
  57. this.el.style.resize = 'none';
  58. }
  59. // run first adjust
  60. this.adjust();
  61. }
  62.  
  63. adjust(): void{
  64. // perform height adjustments after input changes, if height is different
  65. if (this.el.style.height == this.element.nativeElement.scrollHeight + "px") return;
  66. this.el.style.overflow = 'hidden';
  67. this.el.style.height = 'auto';
  68. this.el.style.height = this.el.scrollHeight + "px";
  69. }
  70.  
  71. updateMinHeight(): void{
  72. // Set textarea min height if input defined
  73. this.el.style.minHeight = this._minHeight + 'px';
  74. }
  75.  
  76. updateMaxHeight(): void{
  77. // Set textarea max height if input defined
  78. this.el.style.maxHeight = this._maxHeight + 'px';
  79. }
  80.  
  81.  
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement