Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Socket
Sign inDemoInstall

@bepo65/mat-datatable

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bepo65/mat-datatable

A component for Angular using Angular Material that implements a table as a simplified replacement for ngx-datatable. The project contains a library component and a demo project.


Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

Mat-Datatable

A simple data table with virtual scrolling using Angular Material.

Version [License] Angular version GitHub package.json dependency version (prod)

Table of Contents
  1. About The Project
  2. Getting Started
  3. Used Assets
  4. Mat-Datatable Demo
  5. API Reference
  6. API Testing Harnesses
  7. Roadmap
  8. Hints On Possible Extensions
  9. Contributing
  10. License

About The Project

This project extends 'angular material table' so that it can be used as a replacement for ngx-datatable in one of my projects. Unluckily ngx-datatable seems to be dead as it is still on angular v12 and an update to a more recent angular version is not in sight.

Nat-Datatable implements a table with virtual scrolling, sorting and filtering. Only a minimal set of the functionality of ngx-datatable is implemented.

Screenshot

Try out the live demo.

(back to top)

Getting Started

To use this package in your project just follow these simple steps.

Prerequisites

The package can be used in Angular apps with Angular Material installed.

Installation

Install the package from npmjs

npm install @bepo65/mat-datatable

Embed Mat-Datatable In Your Project

Configure your angular application module (e.g: app.module.ts):

...
import { MatDatatableModule } from 'mat-datatable';

@NgModule({
  ...
  imports: [
    ...
    MatDatatableModule
  ]
})

Add Mat-Datatable to your html file (e.g: app.component.html):

<div class="content-table">
  <mat-datatable #datatable
    [columnDefinitions]="columnDefinitions"
    [displayedColumns]="displayedColumns"
    [dataStoreProvider]="dataStore"
    [trackBy]="trackBy">
    loading...
  </mat-datatable>
</div>

The height of the element containing the mat-datatable must be set explicitly (e.g: app.component.scss):

.content-table {
  height: 400px;
  margin: 0 1em;
  overflow: auto;
}

Some properties of mat-datatable must be configured in the component class (e,g, app.component.ts):

export class AppComponent {
  ...
    protected dataStore = new MyTableDataStore<MyTableItem>();
    protected columnDefinitions: MatColumnDefinition<MyTableItem>[] = [
      {
        columnId: 'id',
        header: 'ID',
        cell: (row: DemoTableItem) => row?.userId?.toString(),
        footer: 'id'
      },
      {
        columnId: 'name',
        sortable: true,
        resizable: true,
        header: 'Name',
        cell: (row: DemoTableItem) => row?.firstName,
        footer: 'name'
      }

    ];
    protected displayedColumns: string[] = ['id', 'name'];

(back to top)

Used Assets

The component is based on Angular Material and uses Google Fonts and the Google Material Icons font. Both fonts are part of the project and not fetched via https.

(back to top)

Mat-Datatable Demo

Demo project to show all features of Mat-Datatable.

git clone git@github.com:BePo65/mat-datatable.git
cd mat-datatable
npm start

Navigate to http://localhost:4200

(back to top)

API Reference

import { MatDatatable } from '@bepo65/mat-datatable';

Classes

MatDatatable

Component to create an angular material table based datatable. The component is generic; the given type is used to define the object for the row data.

Properties
NameDescription
@Input() columnDefinitions: MatColumnDefinition<T>[]The definition of the columns used in the table. The order of the definitions needs not to correspond to the order of the columns in the table. Default value: [].
NameDescription
@Input() displayedColumns: string[]A list with the names of the columns in the table. The array contains the 'columnId' of the corresponding column definition. Default value: [].
NameDescription
@Input() rowSelectionMode: RowSelectionTypeThe type of row selection. Default value: 'none'.
NameDescription
@Input() dataStoreProvider: DataStoreProvider<T>An object that connects the mat-datatable with the data source. The object must be the instance of a class implementing the DataStoreProvider interface. Default value: new EmptyDataStoreProvider<T>.
NameDescription
@Input() trackBy(): TrackByFunction<T>A function that returns a value that identifies a single row. Default value: (index: number, item: T) => JSON.stringify(item).
NameDescription
withFooter: booleanWhether the table has a footer row. Default value: true.
NameDescription
@Output() rowClick: EventEmitter<T>Emitted when a row is clicked.
NameDescription
@Output() rowSelectionChange: EventEmitter<T[]>Emitted when the list of selected rows changes.
NameDescription
@Output() sortChange: EventEmitter<MatSortDefinition[]>Emitted when the sort definition changes.
NameDescription
firstVisibleIndexChanged: Observable<number>Emitted when the index of the first visible row changes.
NameDescription
totalRowsChanged: Observable<number>Emitted when the total number of rows in the datastore changes (does not depend on any active filter).
NameDescription
filteredRowsChanged: Observable<number>Emitted when the number of filtered rows changes.
NameDescription
activatedRow: T | undefinedMarks a row as 'active'.
NameDescription
selectedRows: T[]Marks rows as 'selected'.
NameDescription
sortDefinitions: MatSortDefinition[]Gets / sets the current sort definition.
NameDescription
filterDefinitions: FieldFilterDefinition\<T>[]Gets / sets the current filter definition.
Methods
scrollToRowScrolls to the given row.
Parameters
row: TRow to show on the top of the current viewport.
reloadTableReloads the rows of the table.

Interfaces

DataStoreProvider

Component to create an angular material table based datatable. The component is generic; the given type is used to define the object for the row data.

Methods
getPagedDataFetches data from the datastore respecting sorting and filtering.
Parameters
rowsRange: RequestRowsRangeThe range of rows to fetch.
sorts: FieldSortDefinition[]The sort definitions to use.
filters: FieldFilterDefinition[]The filter definitions to use.
Returns
Observable<Page>Emitting fetched data from the datastore.
MatColumnDefinition

Interface for the definition of a single table column.

Properties
NameDescription
columnId: stringThe ID of the column.
sortable: booleanWhether this column can be used for sorting. By default a column is not sortable.
resizable: booleanWhether this column can be resized. By default a column is not resizable.
header: stringThe text in the header row of a column.
headerAlignment: ColumnAlignmentTypeThe alignment of the header row of a column.
cell: (element: TRowData) => stringThe function to get the content of a cell.
cellAlignment: ColumnAlignmentTypeThe alignment of a data row in a column.
width: stringThe width of the column.
tooltip: (element: TRowData) => stringThe function to get the tooltip for a cell.
showAsMailtoLink: booleanWhether this cell should be shown a 'mailto' link. By default a column is not shown as mailto link.
showAsSingleLine: booleanWhether this cell should be truncated to a single line. By default multiline text in a column is not shown as a single line.
footer: stringThe text in the footer row of a column.
footerAlignment: ColumnAlignmentTypeThe alignment of the footer row of a column.
footerColumnSpan: numberThe number of columns a footer should span. By default a footer spans 1 column.
MatSortDefinition

Interface for the definition of the sorting of 1 table column.

Properties
NameDescription
columnId: stringThe 'columnId' of the column to use for sorting.
direction: SortDirectionThe direction used to sort the column.
Page

Interface defining the properties of a requests for a range of rows.

Properties
NameDescription
startRowIndex: numberThe index of the first row to return.
numberOfRows: numberThe number of rows to return.
RequestRowsRange

Interface defining the properties of a page of rows returned from the datastore.

Properties
NameDescription
content:T[]The array of the requested rows.
startRowIndexThe index of the first row returned.
returnedElementsThe number of rows in 'content'.
totalElementsThe number of rows in the unfiltered data store.
totalFilteredElementsThe number of rows after filtering.

Type Aliases

ColumnAlignmentType

The alignment of the content of a column

type ColumnAlignmentType = "left"
FieldFilterDefinition

The definition of a parameter filtering for the column identified by the given 'fieldName'.

type FieldFilterDefinition = StrictUnion<(FieldFilterDefinitionSimple<T> | FieldFilterDefinitionRange<T>)>;
FieldFilterDefinitionRange

The definition of a parameter filtering for a range of values.

type FieldFilterDefinitionSimple = {
  fieldName: keyof T
  valueFrom: string | number | Date
  valueTo: string | number | Date
};
FieldFilterDefinitionSimple

The definition of a parameter filtering for a single value.

type FieldFilterDefinitionSimple = {
  fieldName: keyof T
  value: string | number | Date
};
FieldSortDefinition

The definition of a single sort parameter.

type FieldSortDefinition = {
  fieldName: keyof T
  sortDirection: SortDirectionAscDesc
};
RowSelectionType

How many rows can be selected.

type RowSelectionType = 'none' | 'single' | 'multi';
SortDirectionAscDesc

The direction of a sort.

type SortDirection = 'asc' | 'desc';

API Testing Harnesses

import { MatDatatableHarness } from '@bepo65/mat-datatable/testing';

Classes

_MatRowCellHarnessBase extends ContentContainerComponentHarness<string>
Methods
static async booleanMatchesChecks if the specified nullable boolean value matches the given value.
Parameters
value: boolean | null | Promise<boolean | null>The nullable boolean value to check, or a Promise resolving to the nullable boolean value.
pattern: boolean | nullThe boolean the value is expected to match. If 'pattern' is 'null', the value is expected to be 'null'.
Returns
Promise<boolean>Whether the value matches the pattern.
async getColumnNameGets the name of the column that the cell belongs to.
Returns
Promise<string>The name of the column that the cell belongs to.
async getColumnWidthGets the cell's width in 'px' (with padding).
Returns
Promise<number>The cell's width.
async getTextGets the cell's text.
Returns
Promise<string>The cell's text.

_MatRowHarnessBase extends ComponentHarness

Abstract class used as base for harnesses that interact with a mat-datatable row.

Methods
async getCellsGets a list of 'MatRowCellHarness', 'MatHeaderCellHarness' or 'MatFooterCellHarness' for all cells in the row.
filter: CellHarnessFilters = {}A set of criteria that can be used to filter a list of cell harness instances.
Returns
Promise<Cell[]>A filtered list of MatRowCellHarness for the cells in the row.
async getCellTextByColumnNameGets the text inside the row organized by columns.
Returns
Promise<MatRowHarnessColumnsText>The text inside the row organized by columns.
async getCellTextByIndexGets the text of the cells in the row.
Parameters
filter: CellHarnessFilters = {}A set of criteria that can be used to filter a list of cell harness instances.
Returns
Promise<string[]>The text of the cells in the row.
static async rowCellsContentMatchChecks if the values of the table row columns given in the 'value' parameter, match the given column values. Only columns defined in the pattern are inspected.
Parameters
value: MatRowHarnessColumnsText | Promise | nullThe nullable object defining all columns of a row and their values used for the checks. Alternatively a Promise resolving to the nullable object.
pattern: Record<string, string | RegExp> | nullObject defining the columns and the values or RegExp expected to match. If 'pattern' is 'null', the value is expected to be 'null'.
Returns
Promise<boolean>Whether the value matches the pattern.

MatDatatableHarness extends ContentContainerComponentHarness<string>

Harness for interacting with a mat-datatable in tests.

Properties
NameDescription
static hostSelector: '.mat-datatable'The selector for the host element of a 'MatDatatableHarness'.
Methods
async getAllChildLoadersGets an array of HarnessLoader instances.
Parameters
selector: stringA string used for selecting the instances.
Returns
Promise<HarnessLoader[]>An array of HarnessLoader instances.
async getAllHarnessesGets an array of harness instances.
Parameters
query: HarnessQueryA query for a ComponentHarness used to filter the instances, which is expressed as either a ComponentHarnessConstructor or a HarnessPredicate.
Returns
Promise<T[]>An array of harness instances.
async getCellTextByColumnNameGets the text inside the entire table organized by columns.
Returns
Promise<MatDatatableHarnessColumnsText>The text inside the entire table organized by columns.
async getCellTextByIndexGets the text inside the entire table organized by rows.
Returns
Promise<string[][]>Array for all rows containing the content of a row as an array.
async getChildLoaderSearches for an element matching the given selector below the root element of this HarnessLoader.
Parameters
selector: stringA string used for selecting the HarnessLoader.
Returns
Promise<HarnessLoader>A new HarnessLoader rooted at the first matching element.
async getFooterRowsGets a list of the footer rows in a mat-datatable.
Returns
Promise<MatHeaderRowHarness[]>A list of the footer rows.
async getHarnessSearches for an instance of the given ComponentHarness class or HarnessPredicate below the root element of this HarnessLoader.
Parameters
query: HarnessQueryA query for a ComponentHarness used to filter the instances, which is expressed as either a ComponentHarnessConstructor or a HarnessPredicate.
Returns
Promise<T>An instance of the harness corresponding to the first matching element.
async getHarnessOrNullGets an instance of the given ComponentHarness class or HarnessPredicate below the root element of this HarnessLoader.
Parameters
query HarnessQueryA query for a ComponentHarness used to filter the instances, which is expressed as either a ComponentHarnessConstructor or a HarnessPredicate.
Returns
Promise<T | null>An instance of the harness corresponding to the first matching element.
async getHeaderRowsGets a list of the header rows in a mat-datatable.
Returns
Promise<MatHeaderRowHarness[]>A list of the header rows.
async getRowsGets a list of the regular data rows in a mat-datatable.
Parameters
filter: RowHarnessFilters = {}A set of criteria that can be used to filter a list of row harness instances.
Returns
Promise<MatRowHarness[]>A filtered list of the regular data rows.
async hasHarnessCheck, if the harness contains the instances defined by 'query'.
Parameters
query HarnessQueryA query for a ComponentHarness used to filter the instances, which is expressed as either a ComponentHarnessConstructor or a HarnessPredicate.
Returns
Promise<boolean>'True', if the instances is part of the harness.
async hostGets a Promise for the 'TestElement' representing the host element of the component.
Returns
Promise<TestElement>The 'TestElement' representing the host element of the component.
static withGets a 'HarnessPredicate' that can be used to search for a mat-datatable with specific attributes.
Parameters
options: TableHarnessFilters = {}Options for narrowing the search.
Returns
HarnessPredicateA 'HarnessPredicate' configured with the given options.

MatFooterCellHarness extends _MatRowCellHarnessBase

Harness for interacting with an MDC-based Angular Material table footer cell.

Properties
static hostSelector: '.mat-mdc-footer-cell'The selector for the host element of a 'MatFooterCellHarness' instance.

MatFooterRowHarness extends _MatRowHarnessBase

Harness for interacting with a mat-datatable footer row.

Properties
static hostSelector: '.mat-mdc-footer-row'Used to identify the host element of a 'MatFooterRowHarness' instance.

MatHeaderCellHarness extends _MatRowCellHarnessBase

Harness for interacting with an MDC-based Angular Material table header cell.

Properties
static hostSelector: '.mat-mdc-header-cell'The selector for the host element of a 'MatHeaderCellHarness' instance.
Methods
async getTextGets the header cell's text.
Return
Promise<string>The header cell's text.
async isResizableCheck, if the cell is defined as 'resizable'.
Returns
Promise<boolean>The cell is resizable.
async resizeResize the cell to a new width (if 'resizable').
Parameters
newWidth: numberThe new width of the cell in 'px'.
Returns
Promise<void>The cell got resized.

MatHeaderRowHarness extends _MatRowHarnessBase

Harness for interacting with a mat-datatable header row.

Properties
static hostSelector: '.mat-mdc-header-row'Used to identify the host element of a 'MatHeaderRowHarness' instance.
Methods
async getCellsGets a list of 'MatRowCellHarness' for all cells in the row.
Parameters
filter: HeaderCellHarnessFilters = {}A set of criteria that can be used to filter a list of cell harness instances.
Returns
Promise<MatHeaderCellHarness[]>A filtered list of MatRowCellHarness for the cells in the header row.

MatMultiSortHarness extends ComponentHarness

Harness for interacting with a mat-multi-sort element in tests.

Properties
static hostSelector: '.mat-multi-sort'Used to identify the elements in the DOM.
Methods
async getActiveHeadersGets all headers used for sorting in the 'mat-multi-sort'.
Returns
Promise<MatMultiSortHeaderHarness[]>All headers used for sorting.
async getActiveSortDataGets the sorting data for all headers used for sorting in the 'mat-multi-sort'.
Returns
Promise<DomSortingDefinition[]>Sorting data of all headers used for sorting.
async getSortHeadersGets the headers used for sorting in the 'mat-multi-sort' reduced by the given 'filter'.
Parameters
filter: MultiSortHeaderHarnessFilters = {}
Returns
Promise<MatMultiSortHeaderHarness[]>The filtered sort headers.
async hostGets a Promise for the 'TestElement' representing the host element of the component.
Returns
Promise<TestElement>The 'TestElement' representing the host element of the component.
static withGets a 'HarnessPredicate' that can be used to search for a 'mat-multi-sort' with specific attributes.
Parameters
options: MultiSortHarnessFilters = {}Options for narrowing the search.
Returns
HarnessPredicate<MatMultiSortHarness>A 'HarnessPredicate' configured with the given options.

MatMultiSortHeaderHarness extends ComponentHarness

Harness for interacting with a mat-multi-sort header element in tests.

Properties
static hostSelectorUsed to identify the elements in the DOM (value: '.mat-multi-sort-header').
Methods
async clickClicks the header to change its sorting direction. Only works if the header is enabled.
Returns
Promise<void>Promise that resolves when the click action completes.
async getAllSortDataGets an object with the sorting data of the header.
Returns
Promise<MatMultiSortHeaderHarnessSortDefinition>The sorting data of the header.
async getIdGets the id of the sort header.
Returns
Promise<string>The id of the sort header.
async getLabelGets the label of the sort header.
Returns
Promise<string>The label of the sort header.
async getSortDirectionGets the sorting direction of the header.
Returns
Promise<SortDirection>The sorting direction of the header.
async getSortPositionGets the sorting position of the header.
Returns
Promise<SortDirection>The sorting position of the header (1..n).
async hostGets a Promise for the 'TestElement' representing the host element of the component.
Returns
PromiseThe 'Promise' for the 'TestElement'.
async isActiveGets whether the sort header is currently being used for sorting.
Returns
PromiseTrue, if the sort header is currently being used for sorting.
async isDisabledWhether the sort header is disabled.
Returns
PromiseTrue, if the sort header is disabled.
static withGets a 'HarnessPredicate' that can be used to search for a sort header with specific attributes.
Parameters
options: MultiSortHeaderHarnessFilters = {}Options for narrowing the search.
Returns
HarnessPredicate<MatMultiSortHeaderHarness>A 'HarnessPredicate' configured with the given options.

MatRowCellHarness extends _MatRowCellHarnessBase

Harness for interacting with a mat-datatable cell in a row.

Properties
static hostSelector: '.mat-mdc-cell'Used to identify the host element of a 'MatRowCellHarness' instance.
Methods
async isSingleLineCheck, if the cell is defined as 'showAsSingleLine'.
Returns
Promise<boolean>The cell is shown as single line.

MatRowHarness extends _MatRowHarnessBase

Harness for interacting with a mat-datatable row.

Properties
static hostSelector: '.mat-mdc-row'Used to identify the elements in the DOM.
Methods
async clickClicks the row (e.g. to select a row).
Returns
Promise<void>Promise that resolves when the click action completes.
static withGets a HarnessPredicate that can be used to search for a mat-datatable row with specific attributes.
Parameters
options: RowHarnessFilters = {}Options for narrowing the search.
Returns
HarnessPredicateA 'HarnessPredicate' configured with the given options.

(back to top)

Interfaces

CellHarnessFilters

A set of criteria that can be used to filter a list of cell harness instances.

Properties
columnName: string | RegExpOnly find instances whose column name matches the given value.
text: string | RegExpOnly find instances whose text matches the given value.
DomSortingDefinition
Properties
id: stringID of the header element.
label: stringLabel of the header.
sortDirection: SortDirectionSort direction of the header.
sortPosition: numberSort position of the header (1..n).
MatDatatableHarnessColumnsText

Text extracted from a table organized by columns.

This interface describes an object, whose keys are the names of the columns and whose values are an object with the following properties:

Properties of a value
text: string[]Array with content of the rows of this column.
headerText: stringContent of the header row of this column.
footerText: string | undefinedContent of the footer row of this column.
MatDatatableHarnessFilters

A set of criteria that can be used to filter a list of table harness instances.

Properties
-
MatRowHarnessColumnsText

Text extracted from a table row organized by columns.

This interface describes an object, whose keys are the names of the columns and whose values are the corresponding cell content.

MultiSortHarnessFilters
Properties
-
MultiSortHeaderHarnessFilters
Properties
label: string | RegExpLabel of the header.
id: string | RegExpID of the header element.
sortDirection: SortDirectionSort direction of the header.
sortPosition: numberSort position of the header (1..n).
RowHarnessFilters

A set of criteria that can be used to filter a list of row harness instances.

Properties
-

(back to top)

Roadmap

See the open issues for a full list of proposed features (and known issues).

(back to top)

Hints On Possible Extensions

  • to make footer turn on / off dynamically it is not sufficient to wrap the footer cell and row definitions in ng-container. Details see stackoverflow. The demo uses ngx-rerender.

(back to top)

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Changelog

The project uses 'standard-version' to create the changelog. To enable this system, commit messages are linted before commits are executed by git.

To enable this system you have to run the following scripts in your local repository home directory:

npx husky install
npx husky add .husky/commit-msg "npx --no -- commitlint --edit $1"

The structure of commit messages is:

  <header>
  <BLANK LINE>
  <body>
  <BLANK LINE>
  <footer>

header

  <type>(<scope>): <short summary>

type and scope

  • build: Changes that affect the build system or external dependencies (example scope: npm)
  • docs: Documentation only changes
  • feat: A new feature
  • fix: A bug fix
  • perf: A code change that improves performance
  • refactor: A code change that neither fixes a bug nor adds a feature
  • test: Adding missing tests or correcting existing tests (example scopes: demo, lib, e2e)

footer

  BREAKING CHANGE: ... (requires MAJOR in Semantic Versioning)

For details of the commit messages format see Contributing to Angular.

(back to top)

License

Distributed under the MIT License. See LICENSE for more information.

This project uses icons from the Google Material Icons Library that are licensed under the Apache License Version 2.0.

(back to top)

FAQs

Package last updated on 02 Mar 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc