ng-grid automatically resizing columns based on content width

I am currently utilizing AngularJS ng-grid and endeavoring to accomplish the following tasks: 1. Adjust column width dynamically based on the content within each column. 2. Automatically resize the last column to fill the remaining space when hiding columns (For instance, if there are 8 columns each with a width of 100 and the total ng-grid width is 800...if 4 columns are hidden, the last column should automatically expand to a width of 500).

At present, I have implemented code for task 1 but it's not functioning as expected (columns are not resizing according to the content). Therefore, I'm seeking assistance in identifying any missing elements and guidance on how to achieve task 2. Thank you


var app = angular.module('myNGridApp', ['ngGrid']);

app.controller('myNGCtrl', function($scope) {
    $scope.myData = [{id: "#4", di: 50, taskstatus: "Lorem Ipsum text", notes: "Lorem Ipsum text", datecreated: "02/04/2014"},
                     {id: "#4", di: 50, taskstatus: "Lorem Ipsum text", notes: "Lorem Ipsum text", datecreated: "02/04/2014"},
                     {id: "#4", di: 50, taskstatus: "Lorem Ipsum text", notes: "Lorem Ipsum text", datecreated: "02/04/2014"},
                     {id: "#4", di: 50, taskstatus: "Lorem Ipsum text", notes: "Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text Lorem Ipsum text ", datecreated: "02/04/2014"},
                     {id: "#4", di: 50, taskstatus: "Lorem Ipsum text", notes: "Lorem Ipsum text", datecreated: "02/04/2014"}];

   $scope.columnDefs= [{ field: 'id', displayName: 'ID', resizable: true, minWidth: 100, width: 'auto' },
                         { field: 'di', displayName: 'DI', resizable: true, minWidth: 100, width: 'auto' },
                         { field: 'taskstatus', displayName: 'Task Status', resizable: true, minWidth: 200, width: 'auto' },
                         { field: 'notes', displayName: 'Notes', resizable: true, minWidth: 400, width: 'auto' },
                         { field: 'datecreated', displayName: 'Date Created', resizable: true, minWidth: 200, width: 'auto' }];

      $scope.gridOptions = { 
        data: 'myData',
        columnDefs: 'columnDefs',
        footerVisible: true,
        enableColumnResize: true,
        filterOptions: {filterText: '', useExternalFilter: false},
        showColumnMenu: true,
        showFilter: true,
        plugins: [new ngGridFlexibleHeightPlugin()],
        virtualizationThreshold: 10,
    };

});

Answer №1

After facing the same challenge, I finally found a solution that met my needs. Hopefully, it can benefit someone else as well!

Essentially, I input the first row of data and an optional object containing user-friendly column names. If certain names are not included or if the object is omitted, the script will automatically format the names by splitting camelCase, replacing underscores and hyphens with spaces, and capitalizing the first letter.

The calculation for column width is based on a monospaced font (such as Lucida Console), using the longer of the column name or the data to determine the width.

if(!datum || datum.toString().length < displayName.length)
  result.width = displayName.length * 7.5;
else
  result.width = datum.toString().length * 7.5;

if(result.width < 40)
  result.width = 40;

Check out the Plunker example here: http://plnkr.co/edit/9SIF0wFYBTW9m5oaXXLb?p=info

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

Display the user's input value in a tooltip without using jQuery

I am looking to achieve this particular layout design. https://i.stack.imgur.com/p9UTH.jpg I am unsure about how to display the input value in the bubble within this layout. The visibility of the bubble should only be triggered on hover. Below is the cod ...

Switching on click using jQuery

I'm having some difficulties with my code and I can't quite figure out how to solve the problem at hand. To be honest, I'm not even sure what the exact question is here. If it seems a bit confusing, I apologize - I'm still new to Jquery ...

Choose a specific option from the dropdown menu using a URL parameter

After reviewing this code snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> // <![CDATA[ $(document).ready(function() { // Parse your query parameters here, and assi ...

Can Regex expressions be utilized within the nodeJS aws sdk?

Running this AWS CLI command allows me to retrieve the correct images created within the past 45 days. aws ec2 describe-images --region us-east-1 --owners self -- query'Images[CreationDate<`2021-12-18`] | sort_by(@, &CreationDate)[].Name&apos ...

Unable to access the contents of an array (React JS)

After fetching the content as an array and viewing its contents with console.log, I noticed that despite the array being populated, it has a length of 0, making it impossible to retrieve its elements using map. What could be causing this issue? https://i. ...

Uppercase the initial letter in a term to indicate a standard condition

I'm struggling to override the CSS in material UI. Even though I tried capitalizing both words, it only changes on selected and hover states, Is there a way to change it in the normal state as well? I've tried debugging but can't seem to fin ...

Inquiry about how TypeScript handles object property references when passed into functions

As a newcomer to TypeScript, I am exploring the creation of a range slider with dual handles using D3.js. I have developed a simple class for managing the slider objects: export class VerticalRangeSlider{ private sliderContainer: d3.Selection<SVGG ...

Leveraging promises with node.js and couched/nano for asynchronous operations

Currently experimenting with the Q promises library in conjunction with couchDB and Nano. The code below is able to display messages in the console, however, it seems that the database is not being created as expected. var nano = require('nano') ...

Transform large GeoJSON files into TopoJSON format

I am struggling to convert a large GeoJSON file that is approximately 1.4GB in size. The command line tool is unable to handle the file due to its filesize. I typically use the topojson command tool like so: topojson {{ input file }} >> {{ output fi ...

What is the best way to arrange an array to display country data based on Covid cases in descending order rather than alphabetical order?

This particular code snippet retrieves Covid19 statistics data using an API. Currently, it displays the data for covid cases of all countries in Alphabetical order. However, I am looking to present the data in descending order, meaning that the country wit ...

Is there a way to determine if a field has been interacted with and meets validation criteria using VeeValidate?

I'm attempting to retrieve the validation flags from a computed property: computed: { isFormValid() { let isValid = this.$validator.fields.some(field => { console.log(field.flags); return field.flags.touched || field.flags.invali ...

Show 1 Blog Post on a Separate AngularJS Page

I would like to show only Test Post 1 on the next HTML page titleDetails.html when the user clicks on Test Post 1 in index.html 1) titleDetails() in index.html: <a ng-click="titleDetails(post)">{{ post.title }} </a> 2) Controller Variables a ...

Issues with jQuery Ajax sending Post data to PHP script

I've been attempting to transfer variables from my JavaScript to a PHP file using AJAX, but for some reason, it's not functioning as expected. Despite researching numerous similar queries, I have yet to come across a solution. Here is an excerpt ...

Swap a jQuery class with another if the class for ul li is currently active

I am currently developing a form builder and I would like to customize the appearance, specifically changing the color of the text. I want the text to be white when the class is set to active, and black when the class is not active. Is there a way to achi ...

Guide to activating "Snapping" feature using the "Select" function in Openlayers 3

I have created an application using OpenLayers 3 that allows users to draw lines or points on a map and add tags to them. While the existing functions in OL3 are helpful for drawing and modifying features, I found it challenging to select the items I drew ...

An element failing to submit using AJAX requests

I have a login form with an <a> element that I want to use for making a post request. However, when I'm examining the backend Django code during debugging, it seems to interpret the request method as GET instead of POST. HTML <form id= ...

Is there a way to determine when the callback function has been called for the final time?

Per the documentation on String.prototype.replace(), if a function is passed to String.replace() with a global regular expression, it will be invoked multiple times. Is there a way to pass a callback within this callback to determine when all invocations ...

Encountering issues accessing the key value 'templateUrl' in Angular6

I have an object in my component.ts file that I need to iterate through in the HTML template using a ui-comp-menu element. menuObject = [{ 'labels': 'Content1', 'templateUrl': 'assets/partials/sample.html ...

Mastering Typing for Enhanced Order Components using Recompose and TypeScript

I have been working on integrating recompose into my react codebase. As part of this process, I have been experimenting with getting some basic functionality to work. While I have made progress, I am uncertain if I am following the correct approach for usi ...

The code stored in Github differs from the code deployed on the production server

I recently took over a project that had been outsourced to a web development company in the past, and it's built on the MEAN stack. After struggling to get the code from the Github repository to work properly, I decided to download the code directly ...