Angular Material UI TextArea Fill Height/Width

Viewed 5032

Using Angular v11 & Angular Material Form field how do I make a textarea mat-form-field take up entire space of container (not auto-grow as I type, but fill the space even if empty)? It should be dynamic solution using CSS only, so as page is resized, so does the text field.

Here's pic of actual page I'm working on. I tried to make sample on stackblitz, however the Material UI doesn't even show properly there - can it? Still hopefully it's helpful to clarify my question.

3 Answers

If I understand correctly your question you can just add this CSS in you style.css file. and add fill-container to the mat-form field element

.mat-form-field.fill-container,
.mat-form-field.fill-container .mat-form-field-infix,
.mat-form-field.fill-container .mat-form-field-flex,
.mat-form-field.fill-container .mat-form-field-wrapper {
  height: 100%;
  width: 100%;
}

.mat-form-field.fill-container textarea {
  height: calc(100% - 25px);
}

in temlplate

<mat-form-field appearance="fill" class="fill-container">
    <mat-label>Textarea</mat-label>
    <textarea matInput [matTextareaAutosize]="false"></textarea>
</mat-form-field>

here is the stackblitz example. https://stackblitz.com/edit/angular-9ms3ph?file=src/app/form-field-overview-example.html

Also if you can use matTextareaAutosize instead of this style, I recommend usage of this @Input property

Like this

<div>
  
  <mat-form-field appearance="fill" class="test">
    <mat-label>Textarea</mat-label>
    <textarea matInput [matTextareaAutosize]="true"></textarea>
  </mat-form-field>

</div>

I know this is not a good idea to do this, but can give a try

<div #parent>

  <!-- ... other elements -->

  <mat-form-field class="textarea-mat-field">
     <mat-label>Text Content</mat-label>
     <textarea 
      matInput  
      placeholder="Enter document text..." 
      #newTextContent
      style="height: {{parent.offsetHeight - newTextContent.getBoundingClientRect().top}}px"></textarea>
  </mat-form-field>
</div>

I found solution finally that is fully dynamic without use of calc or any hard coded adjustments (notice you can add content in section above textarea and it resizes dynamically), see on stackblitz. One of the keys to making it work is this CSS, which I don't quiet understand:

*,
::after,
::before {
  box-sizing: border-box;
}
Related