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

Is there a method available to minimize the size of a local storage list containing strings?

Hey there, I am trying to load a large 2.5MB json file in my browser so that I can use it for some typeAhead functions. Unfortunately, I'm facing an issue with my local storage being constantly full. When using Firefox, I receive the following error ...

swap out a method within a publicly available npm module

Currently, I am using an API wrapper package that utilizes the request module for making API requests. While this setup works well in most cases, I am facing a situation where I need to use this package in a node-webkit environment and replace the request ...

What exactly is the purpose of the script type importmap?

Can you explain the role of <script type="importmap"> and why it has become necessary for my code to function properly? <script type="importmap"> { "imports": { "three": "http ...

What steps should I take to address a problem involving a callback function?

I'm currently working on an application that aims to connect users with friends based on specific questions they answer. However, I keep encountering an error message stating "TypeError [ERR_INVALID_CALLBACK]: Callback must be a function" when the cod ...

When navigating back in Next.js, the URL changes but the content remains the same

I'm currently troubleshooting an issue where the content is not updating when I navigate back using the browser's back button or by setting a button with router.back. The URL updates correctly, but the content remains the same. When I refresh the ...

Creating a specialized Angular directive for handling input of positive numbers

I am working on an application that requires a text field to only accept positive integers (no decimals, no negatives). The user should be restricted to entering values between 1 and 9999. <input type="text" min="0" max="99" number-mask=""> While s ...

Is it possible to instantiate a Backbone view by referencing its string name that is stored within a JavaScript object?

I am currently working on a visual builder that utilizes different views for each component. Each view is defined as shown below: $(function() { var parallaxView = new Backbone.view.extend({ .... }); var parallaxView = new Backbone.view.e ...

How can dependencies be efficiently initialized within Angular applications?

I'm managing an angular website that relies on various external dependencies. However, some of these dependencies are only necessary for a single state and do not need to be loaded during the initial page load. Is there a way to defer the loading of ...

does not output any console log statements

I am attempting to showcase the values of checkboxes on the console, however, it is not working. <input type="checkbox" id="id_price" value="1" onclick="display_img()">Under £200<br> <input type="checkbox" id="id_pr ...

Looking for a particular root node in a tree structure?

I am currently working on converting docx files to xml and using DOM to locate the parent node of a specific element. For instance <chapter> <title> <label>Chapter 1 </label> </title> ...

The JavaScript alert message pops up two times consecutively

I encountered an issue while attempting to utilize a module named disclaimer in Drupal 7. The alert message "You must enter the year you were born in." appears twice and then redirects to a URL that should only be accessed after verifying that you are over ...

Improving sharing functionality across multiple VuGen scripts executed through Performance Center

I have multiple VuGen scripts that utilize the Web/HTTP protocol with javascript. Currently, I am using VuGen 12.53 (patch 4) and have a common login.js action in all of my scripts. Whenever I need to make changes to the login action, I have to update ever ...

When attempting to send emails, SendGrid encounters an error and fails to provide an error code

Earlier today, I successfully sent out a series of emails using SendGrid. It was quite a large number of emails, as I needed to create multiple user accounts with attached email addresses. Thankfully, everything went smoothly and all the emails were delive ...

Something is not quite right when the page is loading in a Ruby on Rails application

In the process of developing a wiki clone, I am faced with an issue involving JavaScript. When I navigate to a specific page by clicking on a link, the JavaScript does not function properly until I refresh the page. The JavaScript aspect mainly involves an ...

Unable to install npm package from git source

I am attempting to install a package from a git repository that I had previously forked. Here is the command I tried: npm i catsaredoomed/invest-openapi-js-sdk --save-dev Unfortunately, I encountered this error message: npm ERR! prepareGitDep 2> npm W ...

Performing a deep insert in SAPUI5 with the Kapsel Offline App on an OData V2 Model

Query: What is the process for performing a "Deep Insert" from a SAPUI5 Client application on an OData V2 Model? Situation: In my SAPUI5 Client application, I need to Deep Insert an "Operation" along with some "Components" into my OData V2 Model. // h ...

ApolloError: Undefined fragment detected and unable to be used

Within the complex structure of my application, I encounter the following: import { gql } from '@apollo/client'; gql` fragment StuffTable on Stuff { id status } `; export const GetStuffDocument = gql` query GetStuff($id: ID!) { ...

There seems to be an issue with the DownloadDir functionality of the node-s3-client library, as

I am currently using a node s3 client library called 'node-s3-client' for syncing directories between S3 and my local server. As per the guidelines provided in the documentation, here is the code I have implemented: var s3 = require('s ...

Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using ...

What is the best way to merge angularjs modules?

In my angularjs application using the codeigniter PHP framework, I have implemented 3 modules - cars.js for car details, cellphones.js for cellphone details, and home.js for home details. Each module caters to a different client's needs. I am trying ...