Alessandro Barros
Alessandro Barros

Reputation: 153

Set the initial height of textarea according to its content

I use a reactive angular form that saves all fields disabled. It turns out that textarea creates a scroll and makes reading difficult for those who are just visualizing.

I already tried with css

 textarea:disabled {
  height: 100%;
  font-size: 13px;
  text-align: justify;
  resize: none;
 }

enter image description here

I would like it to expand according to its content, to behave like a DIV with its due paddings.

Upvotes: 6

Views: 9852

Answers (3)

Alessandro Barros
Alessandro Barros

Reputation: 153

Thanks @adrian Brand from your code I made other Implements and I got the expected result

ngAfterContentChecked() {
    var vtextarea = this.elRef.nativeElement.querySelectorAll('textarea')
    for(let i=0;i<vtextarea.length;i++){
      vtextarea[i].style.height = vtextarea[i].scrollHeight + 'px';      
    }
  }

The css for better viewing without the scrollbars

textarea:disabled{
  height: 100%;
  font-size: 13px;
  text-align: justify;
  resize: none;
  overflow: hidden;

}

Upvotes: 3

Prasanth
Prasanth

Reputation: 124

you can follow this :)

var textarea = document.querySelector('textarea');

textarea.addEventListener('keydown', autosize);
             
function autosize(){
  var el = this;
  setTimeout(function(){
    el.style.cssText = 'height:auto; padding:0';
    // for box-sizing other than "content-box" use:
    // el.style.cssText = '-moz-box-sizing:content-box';
    el.style.cssText = 'height:' + el.scrollHeight + 'px';
  },0);
}
textarea{  
  /* box-sizing: padding-box; */
  overflow:hidden;
  /* demo only: */
  padding:10px;
  width:250px;
  font-size:14px;
  margin:50px auto;
  display:block;
  border-radius:10px;
  border:6px solid #ff0000;
}
<textarea rows='1' placeholder='Auto-Expanding Textarea'></textarea>

Upvotes: 1

Adrian Brand
Adrian Brand

Reputation: 21628

You could make a directive called contentHeight and use it like

<textarea contentHeight></textarea>

and in the directive

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

@Directive({
  selector: '[contentHeight]'
})
export class ContentHeightDirective {

  constructor(private el: ElementRef) { }

  ngOnInit() {
    const nativeElement = this.el.nativeElement;
    nativeElement.style.height = '1px';
    console.log(nativeElement.value)
    nativeElement.style.height = nativeElement.scrollHeight + 'px';
  }
}

https://stackblitz.com/edit/angular-beamvj

Upvotes: 1

Related Questions