1
votes

Currently, I am using the following code to write a directive for auto-sizing a text area depending on user input:

import { ElementRef, HostListener, Directive, OnInit } from '@angular/core';

@Directive({
  selector: 'ion-textarea[autosize]'
})

export class Autosize implements OnInit {
  @HostListener('input', ['$event.target'])
  onInput(textArea:HTMLTextAreaElement):void {
    this.adjust();
  }

  constructor(public element:ElementRef) {
  }

  ngOnInit():void {
    setTimeout(() => this.adjust(), 0);
  }

  adjust():void {
    const textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    textArea.style.height = textArea.scrollHeight + 'px';
  }
}

However, I have been struggling to add a maximum height. Since if the user inputs a really long message, the textarea will expand outside the view. Is there a way I can make it expand until rows of textarea reach 3 and then just work like a normal text area with scroll inside and fixed height?

2

2 Answers

0
votes

You can add maxHeight to your element style.

Here's a working example.

adjust():void {
   const textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
   //textArea.style.overflow = 'hidden';
   textArea.style.height = 'auto';
   textArea.style.height = textArea.scrollHeight + 'px';
   textArea.style.maxHeight = '100px';
}
0
votes

Try setting a css property max-height for your element.