Resize the textarea to fit a maximum of five lines, and display a scrollbar if necessary

Explanation: I am facing an issue in Angular 2 regarding the chat screen. I need the chat screen to dynamically increase in size as I type, up to a maximum of 5 lines, and then show a scrollbar. How can I achieve this functionality?

Problem: The current behavior is not as expected. The scrollbar needs to be limited to 5 lines and the contract/expand feature is not working properly.

Requirement: The chat screen should expand as I type and contract when I press backspace. Once it reaches 5 lines, a scrollbar should appear.

My code:

home.ts

autogrow(){
  let textArea = document.getElementById("textarea")       
  textArea.style.overflow = 'hidden';
  textArea.style.height = '0px';
  textArea.style.height = textArea.scrollHeight + 'px';
}

home.html

<textarea id="textarea" (keyup)="autogrow()" ></textarea>

Answer №1

If you are looking for a solution, consider creating a directive similar to the following example:

    @Directive({
     selector: 'ion-textarea[autosize]'
     })

export class AutoSizeDirective implements OnInit {

  @HostListener('input', ['$event.target'])
  onInput(target): void {
    this.adjust(target);
  }

  @HostListener('focus', ['$event.target'])
  onFocus(target): void {
    this.adjust(target);
  }

  constructor(public element: ElementRef) {}

  ngOnInit(): void {
    setTimeout(() => this.adjust(), 100);
  }

  adjust(textArea: HTMLTextAreaElement = null): void {
    if (textArea == null) {
        textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
    }
    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    textArea.rows = 1;

    if (textArea.scrollHeight < 200) { //or whatever height you like
      textArea.style.height = textArea.scrollHeight + 'px';
    } else {
      textArea.style.height = 200 + 'px';
    }

  }
}

To use it in your HTML, simply add the autosize property within the textarea tag as shown below:

<textarea autosize .....>

Remember to include your directive in app.module as well. I hope this helps resolve your issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a 500 error code while attempting to send a post request using Angular

Whenever I attempt to send a post request to Django server, I encounter a 500 (Internal Server Error) response. Interestingly, the get and put requests work flawlessly on the same server where Django is connected to PostgreSQL database. Here is a snippet ...

Issue with Pagination functionality when using Material-UI component is causing unexpected behavior

My database retrieves data based on the page number and rows per page criteria: const { data: { customerData: recent = null } = {} } = useQuery< .... //removed to de-clutter >(CD_QUERY, { variables: { input: { page: page, perPag ...

Refreshing the sub attributes of an incomplete entity

My Partial object contains sub-properties that may be undefined and need updating. interface Foo { data: string otherData: string } interface Bar { foo: Foo } interface Baz { bar: Bar } let a: Partial<Baz> = {} //... Goal: a.bar.foo ...

Following the upgrade to version 6.3.3, an error appeared in the pipe() function stating TS2557: Expected 0 or more arguments, but received 1 or more

I need some assistance with rxjs 6.3.3 as I am encountering TS2557: Expected at least 0 arguments, but got 1 or more. let currentPath; const pipeArgs = path .map((subPath: string, index: number) => [ flatMap((href: string) => { con ...

I'm having trouble managing state properly in Safari because of issues with the useState hook

Encountering Safari compatibility issues when updating a component's state. Though aware of Safari's stricter mode compared to Chrome, the bug persists. The problem arises with the inputs: Whenever an option is selected from the dropdown, it cl ...

Utilizing PrimeNG Datatable to Connect with an Array of Objects in a Dynamic Manner

I currently have an array of objects with various properties such as: "rows": [ { "id": 1, "createdAt": "2017-07-21T06:05:38.000Z", "updatedAt": "2017-07-21T06:05:38.000Z", "createdBy": null, "modifiedBy": null, "name": "ABC", "owner": "Dian ...

Invoke a function within a component, within that very component

Hey there, I've got an Angular 2 component with a @HostListener. My goal is to call a method from this component using the @HostListener. Check out the code snippet below for my attempt at implementing this: The Component import { Component, Host ...

Exploring the integration of Angular framework with Laravel

Currently, I am coding in Laravel 7 and Angular 10 separately. However, for my upcoming project, I will be incorporating both Laravel and Angular together. My plan is to integrate Angular into my Laravel application and leverage Angular for my JavaScript t ...

How can I delete the black background from the ion-tab-bar in Ionic 7?

In my current project using Ionic 7, I have a navigation guide set up with 4 tabs. I am trying to customize the styling of these ion tabs by adding some custom CSS. The issue I'm facing is that despite my attempts to make the background transparent, ...

Error Encountered: Anticipated 'styles' to consist of a series of string elements

I have attempted various solutions for this particular error message without any success. When launching my angular project using the angular cli via ng serve, everything runs smoothly with no errors. However, upon compiling it with webpack, I encounter th ...

A guide to simulating components using providers in Angular 4 - Achieving successful unit testing

I am struggling with mocking a component that uses providers in Angular 4. Below is the code snippet I am working on: import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; i ...

Updating the `link` function to target a specific DOM element within an Angular 2 component

Angular 1 uses the link function in a directive to target DOM elements. link: function (scope, element, attr) { // do something with element[0], e.g. put generated graphics // inside the node } What is the equivalent feature in Angular 2? ...

Error: The property 'process' cannot be read because it is not defined

Seeking help with a code issue Any advice on best practices would be greatly appreciated. Thank you! An error has occurred: TypeError: Cannot read property 'process' of undefined myComponent.ts ProcessInfo: any | false; showSaveItems = ...

AngularJS Dilemma: Virtual Machine Data Set but No Rendering in Sight

Below is the AngularJS controller code written in Typescript: /// <reference path='../../definitions.d.ts' /> module baseApp.viewControls.products { export interface IProductsScope extends IAppScope { vm: { product ...

Is there a way to make the vss sdk treeview collapse automatically?

Is there a way to have the nodes of a combo control of type TreeView.ComboTreeBehaviorName collapsed by default? I've searched through the documentation at this link and this link, but couldn't find a solution. I also examined the types in vss. ...

Passing data from child components to parent components in NextJs using Typescript

I have created a new component <ConnectWallet setConnected={(t: boolean) => console.log(t)}> <>test</> </ConnectWallet> The component is initialized as follows import { useState, useEffect } from ' ...

Is there a way to eliminate the static keyword from a URL?

I am currently working on a flask(backend)-angular(frontend) application. To compile the angular application, I use the following command: ng build --configuration production --base-href "" The compiled files are stored in the "static" directory ...

Validation messages in an Angular application using Typescript are failing to display or disappear sporadically when applied to an HTML form that has

I am currently working on a simple app that retrieves website content from a CMS [Umbraco]. After making an Ajax call, the form comes back to me as plain HTML. I then append the form to the page and use the Angular $compile service to compile the result. T ...

When transitioning to generics, the narrowing of types in TypeScript is sometimes lost

I am intrigued by this scenario where Test1 fails while Test2 succeeds. I wonder if there is a way to have Test1 pass without altering the generic signature: enum TableType { Shipment = "Shipment", Batch = "Batch", } type Test& ...

What is the method for sending a Post request using the "content type" value of "application/x-www-form-urlencoded"?

Need to send a request to the oAuth2 authentication server to obtain a token. The request works fine in postman but encountering issues when trying to make the same request from Angular 4. CORS configuration is correct as other requests are functioning p ...