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

Enhancing the background of a website with the power of CSS

I am looking to create a customized table without the balls/pots in it. The number of rows on the y-axis will vary depending on the number of names I have, and can be more or less. The values on the x-axis are determined by a parameter included in the URL ...

Next Js is having trouble locating the Service messaging component (firebase-cloud-messaging)

Hey there! I'm currently working on a project with Next JS that involves using Firebase Cloud Messaging. However, I've encountered an error when trying to run or build the project: info - Checking validity of types info - Creating an optimiz ...

The Chocolat.js Lightbox plugin is experiencing issues with jQuery as it is unable to detect the

I am in the process of integrating chocolat.js into a basic website. An issue I encountered was that the thumbnail was directly processing the anchor link, which resulted in the image opening in a new window instead of launching it in a modal on the screen ...

Populate the browser screen with a series of unpredictable numbers

I'm looking to fully populate the visible window of a webpage with random numbers. My current approach involves generating a long string of random digits first, and then applying the following properties to a div: #mydiv{ font-family: "Inconso ...

Display webpage content in an Iframe using Javascript after PHP code has been executed

Despite researching keywords like PHP // Javascript // Load // URL online, I'm still struggling to fully grasp the concepts. Real-life case studies have been helpful, but I must admit that I'm feeling a bit overwhelmed at the moment. I created a ...

Is there a definitive way to distinguish between scrollTop and scrollHeight in web development?

For instance, function checkingScroll(){ var newHeight = element.scrollHeight; var scrollTopValue = element.scrollTop; alert("The scrollHeight property is: " + newHeight + "px"); alert("The scrollTop property is: " + scrollTopValue ...

In ES6, instantiate a fresh new instance of this

Can a new instance of self/this be generated using ES6 inside a static method? For instance; class myClass { static model() { return new this; } } Is there a standard approach for this situation? Thank you very much. ...

Guide to including configuration settings in locals for Sails.js

Currently working on a webapp with Sails.js, I am looking for ways to set up different configurations for development and production modes. Initially, I attempted to store the configuration key in config/local.js, but unfortunately, it did not yield the de ...

The second attempt at an AJAX call is unsuccessful

I am currently developing a form that displays database results based on two entries: Automarke (brand) and Modell (model). You can view the entries here. The Modell dropdown dynamically changes based on the selected Automarke. Here is the code snippet I ...

How can I make sure certain properties in the Vuex store don't retain their state after a redirect during server-side rendering (SSR)?

Our approach involves server-side rendering with the use of preserveState to persist all vuex modules' state when navigating between pages. However, we have a specific store where we need to exclude certain properties from persistence. Is there a sol ...

Leveraging the import statement within lib.d.ts to enhance Intellisense functionality in Visual Studio Code

Looking to streamline my JavaScript project by utilizing custom global variables and harnessing the power of VSCode intellisense for auto completion. Here's what I'm aiming for: See example of auto completion for 'lol' After some sear ...

Navigating between different components in React Router V4 allows for seamless transitions without having to reload the

I am currently learning React with React Router V4 and I have a specific scenario in mind that I would like to achieve, possibly illustrated by the image below: Click on the "Next" button Trigger a click event to Component A ("button got clicked") Upon c ...

Tips for maximizing the efficiency of a callback when utilizing the filter function in Primefaces for 'myDataTable'

Currently using Primefaces 5.1, and I've encountered a situation where I want to hide a table until after the filter is applied in Javascript. My initial thought was to simply set the css of the table to visibility:hidden;, followed by running the fol ...

What is the best way to ensure that the checkbox is not affected when you click on the area?

If the user interacts with the checkbox, I don't want the handleClick function to execute. Is there a way to exclude it or prevent the click event from triggering? <div ... onClick={this.handleClick}> <div> some content here < ...

Troubleshooting: Custom JQuery function not functioning as expected

I am currently facing an issue with the jQuery in my website while trying to implement a portfolio element. It seems to be related to the changePortfolio() function, but I am unsure of how to resolve it. $('.projects a[href^="#"]').on('clic ...

The Angular Material layouts demonstration is experiencing technical difficulties

I'm attempting to run the Angular Material grid layouts demo titled Flex Percent Values, which can be accessed here. Here are some snippets from my HTML code: <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-sc ...

"Learn how to create a scrolling div using a combination of CSS and JavaScript with absolute and relative

After relying solely on "pre-made" components like Mui or TailWind, I decided to create a component using only CSS and maybe JavaScript. However, I encountered some difficulties when attempting to position a div inside an image using relative and absolute ...

Retrieve particular data points from the object based on its unique identifier

Hey there, I'm facing an issue with Angular where I need to retrieve a specific object from an array based on its ID. I'm quite lost on how to approach solving this problem. var Obj = [ { Id: "1", shape: "circle", color: "red" }, { Id: " ...

incapable of destructuring two objects simultaneously

Is there a way to map movies using columns as a property reference? For example: {movies.map(item => {columns.map(column => item.column.path)})} When I try this, the result is always undefined. The 'movies' array contains detailed inform ...

Saving the accurate x and y coordinates into the database

My website features draggable images that each have their own x and y positions. I am attempting to pass these values into a MySQL database, but I'm facing an issue where all the images are getting assigned the same x and y values in the database. In ...