3

I am trying to resize text area automatically to show all text on load without scrolling in Blazor.

<textarea class="form-control" maxlength="255" style="width:250px;" @bind="Comment" id="Comments" required></textarea>

Code:

@code {
    public string Comment = "This is test comments for textarea. This is test comments for textarea.";
  }

The following css i use but not working...

textarea {
  resize: vertical;
  overflow: visible;
  height:auto !important;
}

Thanks in advance.

Osman
  • 1,270
  • 2
  • 16
  • 40

1 Answers1

1

If you are willing to use JSInterop, this will work:

  1. Add a JS function to _Host.cshtml:
...

<script>
  ResizeTextArea = function (id) {
    var el = document.getElementById(id);
    if (el) {
      el.style.height = "5px";
      el.style.height = (el.scrollHeight + 5) + "px";
    }
    return true;
  }
</script>
  1. In your Blazor component, inject IJSRuntime and add the OnAfterRenderAsync event handler to call the JS function:
@page "/interop"
@inject IJSRuntime jsRuntime

<h1>JSInterop</h1>

<textarea 
  class="form-control" maxlength="255" style="width:250px;" 
  @bind="Comment" id="Comments" required>
</textarea>

@code {
    public string Comment = "This is test comments for textarea. This is test comments for textarea.";


    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await jsRuntime.InvokeAsync<bool>("ResizeTextArea", "Comments");
    }
}

Note: the JS function was taken from this SO answer

rk72
  • 976
  • 1
  • 10
  • 15