AgGrid supports multi-line content within its cells

I attempted to utilize this solution, however, it is not functioning properly for me. While it does resize the column height correctly, the text is still not wrapped as expected.

Ag-Grid - Row with multiline text
let gridOptions = {
    columnDefs: columnDefs,
    rowSelection: 'multiple',
    enableColResize: true,
    enableSorting: true,
    enableFilter: true,
    enableRangeSelection: true,
    suppressRowClickSelection: true,
    animateRows: true,
    onModelUpdated: modelUpdated,
    debug: true,
    autoSizeColumns: true,
    getRowHeight: function(params) {
        // assuming 50 characters per line, calculating how many lines are needed
        return 18 * (Math.floor(params.data.zaglavie.length / 45) + 1);
    }
};

function generateRowData() {
    return gon.books;
}

Answer №1

If you're looking to set row heights in a more complicated way, the "Row Height More Complex Example" on the documentation suggests adding CSS to enable text wrapping. To achieve this, simply include

cellStyle: {'white-space': 'normal'}
in your colDef for the specific column (zaglavie as per the example). Check out this plunker for a visual demonstration.

Answer №2

In reference to the field getRowHeight within your gridOptions, I have a suggestion for you that may be more efficient.

ag-grid has the capability to automatically determine the appropriate height for your columns.

According to information found in this article:

Auto Row Height

You can adjust the row height based on the cell contents by setting autoHeight=true for each column where the height should be determined dynamically. For instance, if one column contains description text spanning multiple lines, you can specify that column alone to establish the line height.

Answer №3

Wow! The magic of resetRowHeights()!!

After reading through the suggestions of others, I discovered that you can indicate which columns should have varying heights by using the autoHeight property in the columnDefs. However, when I tried this out, my rows ended up being way too tall. To fix this issue and ensure correct resizing, it is important to also call resetRowHeights() via the grid API's gridReady function.

For instance:

columnDefs.ts <- included in gridOptions configuration

export const columnDefs: Array<any> = [
  {
    headerName: 'Artifact Name',
    field: 'name'
  }, {
    headerName: 'Artifact Type',
    field: 'artifactType',
    width: 40,
    sortable: true
  }, {
    headerName: 'Description',
    field: 'description',
    cellStyle: {'white-space': 'normal'},
    autoHeight: true // <- Works like a charm!
  }
];

X.component.html

      <ag-grid-angular
              class="ag-theme-balham"
              (gridReady)="onGridReady($event)"
              [gridOptions]="gridOptions">
      </ag-grid-angular>

X.component.ts

  onGridReady(grid) {
    grid.api.sizeColumnsToFit();
    grid.api.resetRowHeights();
  }

UPDATE

I'm currently working with Angular 8.

One more tip -- if you're loading rows dynamically, make sure to execute your resets only after the promise has been resolved. This will prevent an unwanted horizontal scroll bar. Learn more about this here:

Answer №5

If you want to insert multiline content, you can follow this method that has proven effective for me.

<style>.cell-wrap {
  white-space: normal !important;
}

</style>
<html>

<body>
  <script>
    // You can include the following code inside the function 'columnDefs'.
    (function() {
      var gridOptions = {
        columnDefs = [{
          headerName: "Name",
          field: "yourField",
          cellRenderer: 'showMultiline',
          cellClass: 'cell-wrap',
          autoHeight: true
        }]
      };

    })();

    function showMultiline() {}
    showMultiline.prototype.init = function(params) {
      // Check if the field has a value
      var cellBlank = !params.value;
      if (cellBlank) {
        return null;
      }

      this.ui = document.createElement('div');
      this.ui.innerHTML = '<div style="font-weight: bold;">' +
        params.value. {
          object
        } +
        "<br/>" +
        params.value. {
          anotherobject
        } +
        "<br/>" +
        '</div>';
    };
    showMultiline.prototype.getGui = function() {
      return this.ui;
    }
  </script>
</body>

</html>

Answer №6

After testing the solution provided in the plnkr shared by Jarod Moser's response, I encountered some challenges due to long words and awkward spacing.

To overcome this, I decided to divide my strings based on spaces and assess how many lines would be needed. However, this approach is not flawless as certain characters occupy less horizontal space than others.

The width of my cell is 200px, allowing approximately 35 characters per line. Code:

gridOptions = {
    // Your other stuff
    getRowHeight: function (params) {
        let newlines = 0;
        var words = params.data.LongestString.split(' ');
        let current = words[0].length;
        while (current > 35) {
            newlines += 1;
            current = current - 35;
        }
        for (var i = 1; i < words.length; i++) {
            let test = current + words[i].length + 1;
            if (test > 35) {
                newlines += 1;
                current = words[i].length;
                while (current > 35) {
                    newlines += 1;
                    current = current - 35;
                }
            }
            else {
                current = test;
            }
        }
        //One line needs 27px, with a line-height of 1.5, every additional line needs 17px.
        return 27 + newlines * 17; 
    },

};

public myColumnDefs = [
    { headerName: 'Header1', field: 'SomeProperty', width: 120 },
    {
        headerName: 'SomeHeader',
        field: 'LongestString',
        width: 200,
        cellStyle: { 'white-space': 'normal', 'line-height': 1.5 } //This is important!!!
    }
    { headerName: 'Header3', field: 'OtherProperty', width: 120 },
];

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

Customizing the display field in an ExtJs Combobox

I am working on a java web application that utilizes an entity class to populate a combobox with ExtJs. The issue I am facing is as follows: Some entries in the displayField may contain html code. To prevent any issues, I used flexjson.HTMLEncoder during ...

Is it possible for an object to be null even when its type is object

There's an issue that I can't seem to replicate. Personally, I'm not experiencing any errors but bugsnag reports that some users are encountering them. Take a look at snippet line 6 for more information. let lang = this.$store.state.lang ...

Canceling a window in JSP and navigating back to the previous page using JavaScript

Here is my Java class controller: public class Controller extends HttpServlet { private Chooser chooser = Chooser.INSTANCE; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOExcep ...

Tips for programmatically adding together numerous input entries within a PHP while loop utilizing java-script on the onfocusout event

Currently, I am working on a method to determine the value of the following id: id="salenag<?php echo $a; ?>". This involves fetching multiple values from a database using PHP and then summing them up before injecting the total into an in ...

recording the results of a Node.js program in PHP using exec

I'm attempting to retrieve the output from my node.js script using PHP exec wrapped within an ajax call. I am able to make the call and receive some feedback, but I can't seem to capture the console.log output in the variable. This is how I exec ...

Having trouble understanding why the other parts of my header are not displaying

<head> This special function runs when the webpage is loaded. <body onload="myOnload()"> A distinctive div at the top with a unique graphic <div id="header"> <img src="resumeheader.png" alt="Header" style="width:750px;h ...

Elevate with Ease: Tailwind's Height Transition

I've been attempting to implement a transition effect using TailwindCSS, but I haven't found an updated version with the latest features. Here's the code snippet: <div id="fadeInElement" className={visible ? " w-2/3 px-5 t ...

What is the best way to obtain the SearchIDs for various searchNames using JavaScript?

Who can assist me in resolving this issue? I am trying to retrieve the id of a searchName whenever a user selects the checkbox. Ideally, I would like to assign the value of the PHP line $search_row->searchid to the id attribute in the input field. Apolog ...

Issue with the react-redux Provider

Whenever I run my basic program Index.js function test(state = []) { return state } const store = createStore(test); render( <Provider store = { store } > <App / > < /Provider > , document.getElementById('root') ...

Express: router.route continues processing without sending the request

I've implemented the following code in my Express application: var express = require('express'); // Initializing Express var app = express(); // Creating our app using Express var bodyParser = require(' ...

Ways to switch up the titles on UploadThing

Recently, I started working with the UploadThing library and encountered a situation where I needed to personalize some names within the code. Here is what I have so far: Below is the snippet of code that I am currently using: "use client"; imp ...

Eliminating redundant values from a JSON object that is nested within another

Currently, I am working on rendering a list of Labels from a local JSON file. However, I am facing the issue of duplicates and I want each label to appear only once. I attempted to use Array.filter() and other methods to achieve this line: "Categories": ob ...

Ajax - Trouble with Updating DIV Content

As a beginner in AJAX, I am encountering difficulties creating a simple AJAX program. My goal is to have a button that, when clicked, changes the text of the div below it. Despite numerous attempts, I have not been able to identify the issue. Below is the ...

Combine various input data and store it in a variable

I am looking for a way to add multiple input text values together and store the sum in a variable. Currently, I can add the values and display it in an id, but I want to assign it to a variable instead. The condition for this variable is described below af ...

Deleting Firestore ancestor documents and sub-collections that do not exist

My goal is to tidy up my collection data. The collection I'm working with is named "teams". Within this collection, there is a sub-collection called "players". I used a basic delete query in Firestore to remove the document under ...

Enhancing URLs with jQuery/AJAX: A Comprehensive Guide to Adding Parameters

Whenever I try to use the get method on an HTML form, the submitted data automatically appears in the URL. You can see what I mean here. Interestingly, when attempting to achieve the same result with JQuery and AJAX using the get method, the data doesn&apo ...

Text Parallax Effect

For my website, I am interested in incorporating a unique parallax effect. Instead of just fixing a background image and allowing scrolling over it, I want to apply this effect to all of the content on my site. The website consists of a single page with m ...

When the time comes, ReactDOM will render your element into the designated container,

What does the [,callback] parameter represent in the ReactDOM.render(element, container) method? ...

Creating a Higher Order Component (HOC) for your Next.js page

Upon running the following code, I encountered an error message Error: The default export is not a React Component in page: "/" pages/index.tsx import React, { useState, useRef } from "react"; import type { NextPage } from "next&q ...

Having trouble with GSAP CDN not functioning properly in your JavaScript or HTML document?

After watching a tutorial on YouTube by Gary Simon, I attempted to animate text using GSAP. Despite following the instructions meticulously and copying the CDN for GSAP and CSSRulePlugin just like him, nothing seems to be happening. Even setting my border ...