Search code examples
angularangular-materialangular-formly

ngx-formly textarea matTextareaAutosize


I'm trying to figure out how to get the textarea to auto resize using matTextareaAutosize in ngx-formly. It works if I add it to the HTML as below

<textarea matInput matTextareaAutosize></textarea>

I have tried to add to the field object and also templateOptions

    {
      key: 'something',
      type: 'textarea',
      templateOptions: {
        label: 'Something'
      },
      matTextareaAutosize: true,
    }

    or

    {
      key: 'something',
      type: 'textarea',
      templateOptions: {
        label: 'Something',
        matTextareaAutosize: true
      }
    }

Solution

  • At the moment of this post, the matTextareaAutosize property is not build in.

    It is very easy to create a custom template. The component look like this:

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { FieldType } from '@ngx-formly/material';
    import { MatInput } from '@angular/material';
    
    @Component({
      template: `
        <textarea matInput
                  [id]="id"
                  [formControl]="formControl"
                  [errorStateMatcher]="errorStateMatcher"
                  [cols]="to.cols"
                  [rows]="to.rows"
                  [placeholder]="to.placeholder"
                  [formlyAttributes]="field"
                  [matTextareaAutosize]="true"
        >
        </textarea>
      `
    })
    
    export class TextareaAutoResizeComponent extends FieldType implements OnInit {
      @ViewChild(MatInput) formFieldControl: MatInput;
      ngOnInit() {
      }
    }
    

    Then define a const for type configuration:

    export const textAreaAutoResizeType = {
      name: 'textarea-auto-resize',
      component: TextareaAutoResizeComponent,
      wrappers: ['form-field']
    };
    

    Finally, register the type in module:

    imports: [
        FormlyModule.forRoot({
          types: [textAreaAutoResizeType]
        })
      ],
    

    Use it like this in components:

    {
        key: 'note',
        type: 'textarea-auto-resize',
        templateOptions: {
           label: 'Note'
        }
    },