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

Execute a function when a button is pressed in a React application

Currently, I am dynamically generating some HTML and have a requirement for certain "events" to trigger an onclick function. The technology stack I am using for this project involves React and TypeScript. My initial approach is as follows: function add_ev ...

Tips for addressing the browser global object in TypeScript when it is located within a separate namespace with the identical name

Currently diving into TypeScript and trying to figure out how to reference the global Math namespace within another namespace named Math. Here's a snippet of what I'm working with: namespace THREE { namespace Math { export function p ...

How can I populate a PrimeNG DataTable with an Array of Objects in Angular 2?

After fetching an array of objects (referred to as devices) from an API using a POST method, I successfully displayed them in a basic HTML table: <table class="table table-striped"> <thead> <tr> <th *ngFor="let property of ...

How can I update the image source using Angular?

<div class="float-right"> <span class="language dashboard" data-toggle="dropdown"> <img class="current" src="us-flag.png" /> </span> <div class="dropdown dashboar ...

Using Jasmine to simulate an if/else statement in Angular/Typescript unit testing

After making a minor change to an existing function, it has been flagged as new code during our quality checks. This means I need to create a unit test specifically for the new 4 lines of code. The challenge is that there was never a unit test in place for ...

Having Trouble Displaying Material UI Icons in Your React App? Here's Why: "Invalid Objects as React Children"

I have been working on a basic app that showcases information about a patient. In this specific component, I am only displaying the name, occupation, and a symbol from Material UI to indicate whether the patient is male or female. However, when I attempt ...

Troubleshooting Angular2: Issues with ngModel functionality within an ngIf directive

Whenever I attempt to reference an NgModel directive using a template reference variable within an *ngIf statement, I encounter a "Cannot read property 'valid' of undefined" error. Consider the following form as an example: <form (ngSubmit)= ...

Exploring Cross-Origin Resource Sharing in ASP.NET Core 2.1 and Angular: A Comprehensive Guide

There has been an abundance of discussions surrounding this topic, but I've yet to find a solution that works for me. My setup includes an asp.net core API 2.1 with an Angular 7 app. Error: "fleet:1 Access to XMLHttpRequest at 'https://loca ...

What is the process of displaying multiple views within a single URL with Ionic?

I wanted to create a layout with both tabs and a navigation bar on the default page of my Ionic application when it starts. After some trial and error, I managed to achieve this functionality by referring to various online resources. However, I am still u ...

The property "property" does not exist within this object

I'm currently developing a peer-to-peer payment system on the Polygon network. I've tried various solutions, such as including any, but none have been successful. Here is the error message I'm encountering: Element implicitly has an 'a ...

Is it possible to create an Angular 2 service instance without relying on the constructor method?

I'm struggling to utilize my ApiService class, which handles API requests, in another class. Unfortunately, I am encountering a roadblock as the constructor for ApiService requires an HttpClient parameter. This means I can't simply create a new i ...

Which would be more effective: implementing Spring Security for role-based authorization, using Angular Route Guards, or combining both approaches?

I'm currently working on a project using Spring Boot for the backend and Angular for the front end. I'm wondering if it's best practice to implement both Spring Security role-based authentication and Angular route guards, or if just using Sp ...

Deploying Firebase functions results in an error

Just recently started exploring Firebase functions. Managed to install it on my computer, but running into an error when trying to execute: === Deploying to 'app'... i deploying firestore, functions Running command: npm --prefix "$RESOURCE_ ...

Using AKS Kubernetes to access a Spring Boot application from an Angular frontend using the service name

I have developed two frontend applications using Angular and a backend application using Spring Boot. Both apps are running in the same namespace. I have already set up two services of type Loadbalancer: The frontend service is named frontend-app-lb (exp ...

What is the approach to merge an inner observable in RxJs with the outer observable and produce a single array as output

Whenever I execute the following code: timer(1000).pipe( expand(() => of('a')), take(3) ) .subscribe(data => alert(data)); I receive three alerts: one with 0, another with 'a', and a third one also with 'a'. I wo ...

Issue TS2349 occurs when attempting to use a combination of boolean and function types within union typing

In my class, there is a property called "isVisible" which can be either a boolean value or a function that returns a boolean. The code snippet below demonstrates what I am currently using. It works fine and achieves the desired result, but during compilat ...

Build upon a class found in an AngularJS 2 library

Whenever I attempt to inherit from a class that is part of a library built on https://github.com/jhades/angular2-library-example For example, the class in the library: export class Stuff { foo: string = "BAR"; } And the class in my application: exp ...

Discover the location of the class definition in VSCode with this helpful clue

Here is the code snippet I am working with: const Gatherer = require('../gatherer'); class MetaRobots extends Gatherer { /** * @param {{driver: !Driver}} options Run options … } module.exports = MetaRobots; When using VSCode, Driver ...

What are the steps for integrating Angular Material into an existing project?

I have recently set up an Angular 2 project. Attempting to integrate Angular Material into my existing project, I followed the steps outlined in the official documentation by running the npm command: npm install --save @angular/material @angular/cdk How ...

Exploring Angular 4's Capabilities: Navigating a Multi-Dimensional Array

I am currently working with a multi-dimensional array that has two keys, and it is structured as follows: user: any = {}; // The index is incremented within a for loop to add values to the user object (this part is functioning correctly) this.user[index++ ...