0.0.10 • Published 6 years ago

ngx-mui-datatables v0.0.10

Weekly downloads
10
License
MIT
Repository
github
Last release
6 years ago

NGX-MUI-Datatables - Datatables for Material-UI(Angular)

Build Status NPM Downloads Coverage Status dependencies Status npm version

This library is based off of the MUI-Datatables. The original library was written in react, and this simply provides a compatability layer between angular and the library, providing access to the bindings and other properties that the library offers.

Link to original library on github

MUI-Datatables is a data tables component built on Material-UI. It comes with features like filtering, resizable + view/hide columns, search, export to CSV download, printing, selectable rows, expandable rows, pagination, and sorting. On top of the ability to customize styling on most views, there are two responsive modes "stacked" and "scroll" for mobile/tablet devices.

Install

npm install ngx-mui-datatables --save or with yarn yarn add ngx-mui-datatables

This library also requires you to install the following libraries npm install @material-ui/icons npm install @material-ui/core or with yarn yarn add @material-ui/icons yarn add @material-ui/core

Usage

Add the following line to your polyfills.ts file. This will fix an error caused by using a react framework in angular.

(window as any).global = window;

Add the NgxMuiDatatableModule to your app module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { NgxMuiDatatablesModule } from 'ngx-mui-datatables';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    NgxMuiDatatablesModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

For a simple table:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  columns = ['Name', 'Company', 'City', 'State'];

  data = [
    ['Joe James', 'Test Corp', 'Yonkers', 'NY'],
    ['John Walsh', 'Test Corp', 'Hartford', 'CT'],
    ['Bob Herm', 'Test Corp', 'Tampa', 'FL'],
    ['James Houston', 'Test Corp', 'Dallas', 'TX'],
  ];

  options = {
    filterType: 'checkbox',
  };
}
<ngx-mui-datatable title="Employee List" [data]="data" [columns]="columns" [options]="options"></ngx-mui-datatable>

Or customize columns:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  columns = [
    {
      name: 'name',
      label: 'Name',
      options: {
        filter: true,
        sort: true,
      }
    },
    {
      name: 'company',
      label: 'Company',
      options: {
        filter: true,
        sort: false,
      }
    },
    {
      name: 'city',
      label: 'City',
      options: {
        filter: true,
        sort: false,
      }
    },
    {
      name: 'state',
      label: 'State',
      options: {
        filter: true,
        sort: false,
      }
    },
  ];

  data = [
    { name: 'Joe James', company: 'Test Corp', city: 'Yonkers', state: 'NY' },
    { name: 'John Walsh', company: 'Test Corp', city: 'Hartford', state: 'CT' },
    { name: 'Bob Herm', company: 'Test Corp', city: 'Tampa', state: 'FL' },
    { name: 'James Houston', company: 'Test Corp', city: 'Dallas', state: 'TX' },
  ];

  options = {
    filterType: 'checkbox',
  };
}

API

The component accepts the following props:

NameTypeDescription
titlearrayTitle used to caption table
columnsarrayColumns used to describe table. Must be either an array of simple strings or objects describing a column
dataarrayData used to describe table. Must be an array containing objects. (Arrays containing just strings or numbers also supported)
optionsobjectOptions used to describe table

Options:

NameTypeDefaultDescription
pagenumberUser provided starting page for pagination
countnumberUser provided override for total number of rows
serverSidebooleanfalseEnable remote data source
rowsSelectedarrayUser provided selected rows
filterTypestringChoice of filtering view. enum('checkbox', 'dropdown', 'multiselect', 'textField')
textLabelsobjectUser provided labels to localize text
paginationbooleantrueEnable/disable pagination
selectableRowsstring'multiple'Numbers of rows that can be selected. Options are "multiple", "single", "none".
isRowSelectablefunctionEnable/disable selection on certain rows with custom function. Returns true if not provided. function(dataIndex) => bool
resizableColumnsbooleanfalseEnable/disable resizable columns
expandableRowsbooleanfalseEnable/disable expandable rows
customToolbarfunctionRender a custom toolbar
customToolbarSelectfunctionRender a custom selected rows toolbar. function(selectedRows, displayData, setSelectedRows) => void
customFooterfunctionRender a custom table footer. function(count, page, rowsPerPage, changeRowsPerPage, changePage) => string
customSortfunctionOverride default sorting with custom function. function(data: array, colIndex: number, order: string) => array
customSearchfunctionOverride default search with custom function. customSearch(searchQuery: string, currentRow: array, columns: array) => boolean
elevationnumber4Shadow depth applied to Paper component
caseSensitivebooleanfalseEnable/disable case sensitivity for search
responsivestring'stacked'Enable/disable responsive table views. Options: 'stacked', 'scroll'
rowsPerPagenumber10Number of rows allowed per page
rowsPerPageOptionsarray10,15,20Options to provide in pagination for number of rows a user can select
rowHoverbooleantrueEnable/disable hover style over rows
fixedHeaderbooleantrueEnable/disable fixed header columns
sortFilterListbooleantrueEnable/disable alphanumeric sorting of filter lists
sortbooleantrueEnable/disable sort on all columns
filterbooleantrueShow/hide filter icon from toolbar
searchbooleantrueShow/hide search icon from toolbar
searchTextstringInitial search text
printbooleantrueShow/hide print icon from toolbar
downloadbooleantrueShow/hide download icon from toolbar
downloadOptionsobjectOptions to change the output of the CSV file. Default options: {filename: 'tableDownload.csv', separator: ','}
onDownloadfunctionA callback function that triggers when the user downloads the CSV file. In the callback, you can control what is written to the CSV file. function(buildHead: (columns) => string, buildBody: (data) => string, columns, data) => string
viewColumnsbooleantrueShow/hide viewColumns icon from toolbar
onRowsSelectfunctionCallback function that triggers when row(s) are selected. function(currentRowsSelected: array, allRowsSelected: array) => void
onRowsDeletefunctionCallback function that triggers when row(s) are deleted. function(rowsDeleted: object(lookup: {dataindex: boolean}, data: arrayOfObjects: {index, dataIndex})) => void OR false (Returning false prevents row deletion.)
onRowClickfunctionCallback function that triggers when a row is clicked. function(rowData: string[], rowMeta: { dataIndex: number, rowIndex: number }) => void
onCellClickfunctionCallback function that triggers when a cell is clicked. function(colData: any, cellMeta: { colIndex: number, rowIndex: number, dataIndex: number }) => void
onChangePagefunctionCallback function that triggers when a page has changed. function(currentPage: number) => void
onChangeRowsPerPagefunctionCallback function that triggers when the number of rows per page has changed. function(numberOfRows: number) => void
onSearchChangefunctionCallback function that triggers when the search text value has changed. function(searchText: string) => void
onSearchOpenfunctionCallback function that triggers when the searchbox opens. function() => void
onFilterChangefunctionCallback function that triggers when filters have changed. function(changedColumn: string, filterList: array) => void
onColumnSortChangefunctionCallback function that triggers when a column has been sorted. function(changedColumn: string, direction: string) => void
onColumnViewChangefunctionCallback function that triggers when a column view has been changed. function(changedColumn: string, action: string) => void
onTableChangefunctionCallback function that triggers when table state has changed. function(action: string, tableState: object) => void
setRowPropsfunctionIs called for each row and allows to return custom props for this row based on its data. function(row: array, dataIndex: number) => object

Customize Columns

On each column object, you have the ability to customize columns to your liking with the 'options' property. Example:

const columns = [
 {
  name: "Name",
  options: {
   filter: true,
   sort: false
  }
 },
 ...
];

Column:

NameTypeDescription
namestringName of column (This field is required)
labelstringColumn Header Name override
optionsobjectOptions for customizing column

Column Options:

NameTypeDefaultDescription
displaystring'true'Display column in table. enum('true', 'false', 'excluded')
emptybooleanfalseThis denotes whether the column has data or not (for use with intentionally empty columns)
viewColumnsbooleantrueAllow user to toggle column visibility through 'View Column' list
filterListarrayFilter value list Example
filterOptionsarrayFilter options Example
customFilterListRenderfunctionFunction that returns a string used as the chip label. function(value) => string Example
filterbooleantrueDisplay column in filter list
filterTypestring'dropdown'Choice of filtering view. Takes priority over global filterType option.enum('checkbox', 'dropdown', 'multiselect', 'textField').
sortbooleantrueEnable/disable sorting on column
searchablebooleantrueExclude/include column from search results
sortDirectionstringSet default sort order enum('asc', 'desc')
printbooleantrueDisplay column when printing
downloadbooleantrueDisplay column in CSV download file
hintstringDisplay hint icon with string as tooltip on hover.
customHeadRenderfunctionFunction that returns a string. Used as display for column header. function(columnMeta, handleToggleColumn) => string
customBodyRenderfunctionFunction that returns a string. Used as display data within all table cells of a given column. function(value, tableMeta, updateValue) => string Example
setCellPropsfunctionIs called for each cell and allows to return custom props for this cell based on its data. function(cellValue: string, rowIndex: number, columnIndex: number) => object

customHeadRender is called with these arguments:

function(columnMeta: {
  customHeadRender: func,
  display: enum('true', 'false', 'excluded'),
  filter: bool,
  sort: bool,
  sortDirection: bool,
  download: bool,
  empty: bool,
  index: number,
  label: string,
  name: string,
  print: bool,
  searchable: bool,
  viewColumns: bool
}, handleToggleColumn: function(columnIndex))

customBodyRender is called with these arguments:

function(value: any, tableMeta: {
  rowIndex: number,
  columnIndex: number,
  columnData: array, // Columns Options object
  rowData: array, // Full row data
  tableData: array, Full table data
  tableState: {
    announceText: null|string,
    page: number,
    rowsPerPage: number,
    filterList: array,
    selectedRows: {
      data: array,
      lookup: object,
    },
    showResponsive: boolean,
    searchText: null|string,
  },
}, updateValue: function)

Customize Styling

The original library provided a way to style the components, however for the moment it is not supported in this version. An oficial way may come in the future, but not at this point in time.

Remote Data

If you are looking to work with remote data sets or handle pagination, filtering, and sorting on a remote server you can do that with the following options:

const options = {
  serverSide: true,
  onTableChange: (action, tableState) => {
    this.xhrRequest('my.api.com/tableData', result => {
      this.setState({ data: result });
    });
  }
};

To see an example Click Here

Localization

This package decided that the cost of bringing in another library to perform localizations would be too expensive. Instead the ability to override all text labels (which aren't many) is offered through the options property textLabels. The available strings:

const options = {
  ...
  textLabels: {
    body: {
      noMatch: "Sorry, no matching records found",
      toolTip: "Sort",
    },
    pagination: {
      next: "Next Page",
      previous: "Previous Page",
      rowsPerPage: "Rows per page:",
      displayRows: "of",
    },
    toolbar: {
      search: "Search",
      downloadCsv: "Download CSV",
      print: "Print",
      viewColumns: "View Columns",
      filterTable: "Filter Table",
    },
    filter: {
      all: "All",
      title: "FILTERS",
      reset: "RESET",
    },
    viewColumns: {
      title: "Show Columns",
      titleAria: "Show/Hide Table Columns",
    },
    selectedRows: {
      text: "row(s) selected",
      delete: "Delete",
      deleteAria: "Delete Selected Rows",
    },
  }
  ...
}

License

The files included in this repository are licensed under the MIT license.

Thanks

Thank you to BrowserStack for providing the infrastructure that allows us to test in real browsers.

Thank you to the original author of this library MUIDataTables.

0.0.10

6 years ago

0.0.9

6 years ago

0.0.8

6 years ago

0.0.7

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago