Modifying the functionality of "Export all data as csv" in Angular UI Grid

In my uigrid, I have numerous column definitions that remain unfilled with data initially to prevent a large dataset. Instead, the requested column data is retrieved when the column visibility changes.

However, this setup causes an issue with the csv exporter functionality. When users opt for "Export all data as csv," they end up with multiple empty columns.

My goal is to modify the default behavior of the existing csv menu items by utilizing uiGridExporterConstants.VISIBLE.

I intended to create custom menu items like so:

  $scope.gridOptions.exporterMenuCsv = false; //Creating custom menu items to exclude invisible columns
  $scope.gridOptions.gridMenuCustomItems = [
      {
          title: 'Export All to CSV',
          action: function ($event) {
              var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
              $scope.gridApi.exporter.csvExport( uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, myElement );
          }
      },{
          title: 'Export Selected to CSV',
          action: function ($event) {
              var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
              $scope.gridApi.exporter.csvExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE, myElement );
          }
      },{
          title: 'Export Visible to CSV',
          action: function ($event) {
              var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
              $scope.gridApi.exporter.csvExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE, myElement );
          }
      }
  ];

However, only the first item seems to appear. It might be necessary to use addToGridMenu, but I am uncertain. Ideally, I would prefer to keep the default items intact and only adjust the "export all data as csv" option to export visible columns exclusively.

Answer №1

To implement the required functionality, I utilized gridApi.core.addToGridMenu as shown below:

    $scope.gridOptions = {
            exporterCsvLinkElement: angular.element(document.querySelectorAll('.custom-csv-link-location')),
            onRegisterApi: function(gridApi){
                $scope.gridApi = gridApi;

                $interval(function () {
                    gridApi.core.addToGridMenu(gridApi.grid, [{
                        title: 'Export All to CSV',
                        order: 1,
                        action: function ($event) {
                            var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
                            $scope.gridApi.exporter.csvExport(uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, myElement);
                        }
                    }]);
                    gridApi.core.addToGridMenu(gridApi.grid, [{
                        title: 'Export Visible to CSV',
                        order: 2,
                        action: function ($event) {
                            var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
                            $scope.gridApi.exporter.csvExport(uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE, myElement);
                        }
                    }]);
                }, 0, 1);

                $scope.gridApi.selection.on.rowSelectionChanged($scope, function () { //for single row selection
                    if (gridApi.grid.selection.selectedCount > 0 && !selectionMenuAdded) { //only add menu item if something is selected and if the menu item doesn't already exist
                        selectionMenuAdded = true;
                        gridApi.core.addToGridMenu(gridApi.grid, [{
                            title: 'Export Selected to CSV',
                            order: 3,
                            id: 'uiSel',
                            action: function ($event) {
                                if (gridApi.grid.selection.selectedCount > 0) {
                                    var uiExporter = uiGridExporterService;
                                    var grid = $scope.gridApi.grid;
                                    uiExporter.loadAllDataIfNeeded(grid, uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE).then(function () {
                                        var exportColumnHeaders = uiExporter.getColumnHeaders(grid, uiGridExporterConstants.VISIBLE);
                                        var selectionData = [];
                                        gridApi.selection.getSelectedRows().forEach(function (entry) {
                                            var innerData = [];
                                            for (var e in entry) { //create the inner data object array
                                                if (e !== '$$hashKey') {
                                                    var selectObj = { value: entry[e] };
                                                    innerData.push(selectObj);
                                                }
                                            }
                                            selectionData.push(innerData); //push the inner object value array to the larger array as required by formatAsCsv
                                        });
                                        var csvContent = uiExporter.formatAsCsv(exportColumnHeaders, selectionData, grid.options.exporterCsvColumnSeparator);
                                        uiExporter.downloadFile($scope.gridOptions.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility);
                                    });
                                }
                            }
                        }]);
                    } else if (gridApi.grid.selection.selectedCount === 0 && selectionMenuAdded) {
                        selectionMenuAdded = false;
                        gridApi.core.removeFromGridMenu(gridApi.grid, 'uiSel');
                    }
                });

                $scope.gridApi.selection.on.rowSelectionChangedBatch($scope, function () {
                    if (gridApi.grid.selection.selectedCount > 0 && !selectionMenuAdded) {
                        selectionMenuAdded = true;
                        gridApi.core.addToGridMenu(gridApi.grid, [{
                            title: 'Export Selected to CSV',
                            order: 3,
                            id: 'uiSel',
                            action: function ($event) {
                                if (gridApi.grid.selection.selectedCount > 0) {
                                    var uiExporter = uiGridExporterService;
                                    var grid = $scope.gridApi.grid;
                                    uiExporter.loadAllDataIfNeeded(grid, uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE).then(function () {
                                        var exportColumnHeaders = uiExporter.getColumnHeaders(grid, uiGridExporterConstants.VISIBLE);
                                        var selectionData = [];
                                        gridApi.selection.getSelectedRows().forEach(function (entry) {
                                            var innerData = [];
                                            for (var e in entry) {
                                                if (e !== '$$hashKey') {
                                                    var selectObj = { value: entry[e] };
                                                    innerData.push(selectObj);
                                                }
                                            }
                                            selectionData.push(innerData);
                                        });
                                        var csvContent = uiExporter.formatAsCsv(exportColumnHeaders, selectionData, grid.options.exporterCsvColumnSeparator);
                                        uiExporter.downloadFile($scope.gridOptions.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility);
                                    });
                                }
                            }
                        }]);
                    } else if (gridApi.grid.selection.selectedCount === 0 && selectionMenuAdded) {
                        selectionMenuAdded = false;
                        gridApi.core.removeFromGridMenu(gridApi.grid, 'uiSel');
                    }
                });
          }
    }

Make sure to include uiGridExporterConstants and uiGridExporterService as dependencies.

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

Transferring temporary information from server to controller using angular-file-upload

Currently, I am utilizing the angular-file-upload library which can be found at this link: https://github.com/danialfarid/angular-file-upload. In the example provided on that page, data from a file is sent to the backend from a controller using the availab ...

The URL may change, but the component remains constant when navigating back

My application consists of two primary components: the Project component and MainContainer. The MainContainer component regularly fetches data using a fetchData method. When moving forward, both the URL and component can change dynamically. However, when m ...

Collaborate and connect a single store for both vue and electron applications

Storing data within electron's main.js to display reactively in a vue window has been a bit challenging. I have a store set up in store/index.js with state and mutations, which works fine when accessed individually from electron and vue. However, the ...

Discovering inappropriate behavior in filtered results

I am attempting to locate projects based on their project IDs. To achieve this, I am utilizing the following filter method: $scope.filteredPro = $filter('filter')( project.ProjectSummaryFilter, {"ProjectId" : "1" } ); However, the issue arises ...

Troubleshooting Next.js and NextAuth.js Authentication Redirect Issue

I am experiencing a problem with authentication in my Next.js application using NextAuth.js. The issue specifically pertains to the redirection after successful login. Here is an overview of my setup: NextAuth.js Configuration (app/api/auth/[...nextauth.js ...

Choose a random element from an array and then modify the array

Can someone please assist me with this task? I am creating an array that corresponds to specific question numbers. var arrayCharge = []; for (var i = 2; i <= 45; i++) { arrayCharge.push(i); } I then utilize these numbers to display the respective quest ...

Choose a value from a dropdown menu in Angular

Currently, I am developing an angularjs application and encountering difficulties setting the selected value in a select tag. Please note that the 2nd option has the selected="selected" I have tried various solutions such as setting the doc type to HTML5 ...

PHP is hindered by JavaScript when attempting to export MySQL

Using the php code displayed below, I am able to export data from my mysql database: <?php require_once('connect.php'); $group = 1;//$_GET['group']; $export = mysql_query ("SELECT * FROM relationship WHERE group_id = $group"); ...

Tips for dynamically incorporating input forms within AngularJS

I am trying to dynamically change the form inputs using ng-bind-html. However, I am only able to display the label and not the text box on the DOM. The content inside ctrl.content will depend on the values received from the server. Important Note: The ...

How to align the markup of a dynamic directive with its host in Angular?

Introducing a simple directive called [popover], its main purpose is to dynamically inject a component (as a sibling). Implementation example: @Component({ selector: 'my-app', template: ` <div> <button popover>Popover ...

Is it a Javascript comparison glitch, or have I overlooked something important?

Recently, I've been working on a JavaScript code that is designed to retrieve data from a server regarding the temperature readings from 2 sensors. The data is stored in a text file where each line includes a date along with 2 values corresponding to ...

Flexlayout for React.js Native is a powerful tool that allows

I am currently working on building a Flexbox Layout using React.js. Code: for(let i = 0; i < 10; i++){ articles.push( <View key={i} style={{height:120, flex:1}}> <View style={{flexDirection: 'column' , flex:1, height ...

No Track Duration Found in the Last.FM API

I am currently working on a small app using the Last.fm API for personal use. However, I am facing an issue with fetching and rendering Track Duration data. After making the AJAX request, I can successfully log the Track Duration to the console and append ...

Why is jQuery button function only functioning for the first button?

I'm encountering an issue with my table of records. Each row in the table has a submit button that triggers an AJAX request to the server when clicked. Strangely, the first button works perfectly and sends the request as expected. However, subsequent ...

Tips for Managing Disconnection Issues in Angular 7

My goal is to display the ConnectionLost Component if the network is unavailable and the user attempts to navigate to the next page. However, if there is no network and the user does not take any action (doesn't navigate to the next page), then the c ...

Is there a way to prevent the Alt+F4 function from closing tabs in the Internet Explorer browser

Ctrl+W and Alt+F4 can be used to close the IE browser, but I am looking to disable this default action. While I have found a way to handle the Ctrl+W command, I am struggling with disabling the Alt+F4 event. It seems that other Alt+Key events like Alt+En ...

How come I am encountering an Uncaught TypeError when attempting to execute 'appendChild' on 'Node' with this draggable code?

I have been working on incorporating this code snippet from Web Dev Simplified into my project: JS: const draggables = document.querySelectorAll('.draggable') const containers = document.querySelectorAll('.drag-container') draggables. ...

Is there a way to determine if a user has the ability to navigate forward in Next.js?

I am faced with a challenge of determining whether a user can navigate forward on a webpage. My goal is to have two buttons - one to go back and another to go forward, with the forward button disabled when navigation is not possible. For the back button f ...

Convert the easeInExpo function from jQuery easing to vanilla JavaScript and CSS

Currently, I am in the process of converting a piece of code from jQuery to plain JavaScript and CSS. The specific code snippet I am focusing on involves creating easing functions without relying on jQuery. const customEasing = { easeInExpo: function ( ...

Customize the Color of Your Material-UI Drawer

Need help with setting the background color of a Material-UI Drawer. I tried using the following code but it didn't work: const styles = { paper: { background: "blue" } } After defining the styles, I passed them to the Drawer component like ...