Search code examples
cssangularangular-material

Angular Material input - textarea with grow in flexbox


I want to let the textarea flexible grow depending on the what space is available.

So basically if I have the

<form>
  <mat-form-field class="example-full-width area-1">
    <mat-label>Leave a comment</mat-label>
    <textarea matInput placeholder="Ex. It makes me feel..."></textarea>
  </mat-form-field>

  <mat-form-field class="example-full-width area-2" >
    <mat-label>Leave a comment</mat-label>
    <textarea matInput placeholder="Ex. It makes me feel..."></textarea>
  </mat-form-field>
</form>

I would expect that the input area grows as well. I'm aware that there exists the directive cdkTextareaAutosize but this will let the textarea grow depending on the input. Which I don't want to have.

I would like to have the textarea stretched over the whole height and not only to a small part. I want to have some kind of dynamic approach - depending where I place the component.

Stackblitz

enter image description here


Solution

  • The below CSS might work, we can just adjust so that it's always 100% based on flexbox styles and height:100%, we use display: flex and flex-grow: 1 to make the boxes fit the available space:

    ::ng-deep {
      .full-textarea {
        display: flex;
        mat-form-field {
          display: flex;
          flex-grow: 1;
          .mat-mdc-form-field-flex,
          .mat-mdc-form-field-infix,
          textarea {
            height: 100% !important;
          }
        }
      }
    }
    

    html

    <form class="full-textarea">
      <mat-form-field class="example-full-width area-1">
        <mat-label>Leave a comment</mat-label>
        <textarea matInput placeholder="Ex. It makes me feel..."></textarea>
      </mat-form-field>
    
      <mat-form-field class="example-full-width area-2">
        <mat-label>Leave a comment</mat-label>
        <textarea matInput placeholder="Ex. It makes me feel..."></textarea>
      </mat-form-field>
    </form>
    

    Stackblitz Demo