├── .all-contributorsrc
├── .editorconfig
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── README.md
├── angular.json
├── commitlint.config.js
├── package-lock.json
├── package.json
├── projects
├── demo
│ ├── browserslist
│ ├── karma.conf.js
│ ├── src
│ │ ├── app
│ │ │ ├── app.component.spec.ts
│ │ │ ├── app.component.ts
│ │ │ ├── app.module.ts
│ │ │ ├── generic-table
│ │ │ │ ├── generic-table.component.html
│ │ │ │ ├── generic-table.component.scss
│ │ │ │ └── generic-table.component.ts
│ │ │ ├── person-service.ts
│ │ │ └── reactive-table
│ │ │ │ ├── reactive-table.component.html
│ │ │ │ ├── reactive-table.component.scss
│ │ │ │ └── reactive-table.component.ts
│ │ ├── assets
│ │ │ └── .gitkeep
│ │ ├── environments
│ │ │ ├── environment.prod.ts
│ │ │ └── environment.ts
│ │ ├── favicon.ico
│ │ ├── index.html
│ │ ├── main.ts
│ │ ├── polyfills.ts
│ │ ├── styles.scss
│ │ └── test.ts
│ ├── tsconfig.app.json
│ ├── tsconfig.spec.json
│ └── tslint.json
└── generic-material-tables
│ ├── README.md
│ ├── ng-package.json
│ ├── package.json
│ ├── src
│ ├── lib
│ │ ├── data-source
│ │ │ ├── generic-table-data-source.ts
│ │ │ └── reactive-generic-table-data-source.ts
│ │ ├── filtering
│ │ │ ├── column-filter-predicate.ts
│ │ │ ├── data-source-filter-predicate.ts
│ │ │ ├── default-column-filter-predicate.ts
│ │ │ └── generic-filter-predicate.fn.ts
│ │ ├── internals
│ │ │ ├── loading
│ │ │ │ ├── loadable.ts
│ │ │ │ ├── map-to-loadable.operator.spec.ts
│ │ │ │ └── map-to-loadable.operator.ts
│ │ │ └── read-property.fn.ts
│ │ └── sorting
│ │ │ ├── apply-mat-sort.directive.ts
│ │ │ ├── generic-sorting-accessor.fn.ts
│ │ │ ├── persisted-sort.directive.ts
│ │ │ └── sort.module.ts
│ └── public-api.ts
│ ├── tsconfig.lib.json
│ └── tslint.json
├── tsconfig.json
├── tslint.json
└── yarn.lock
/.all-contributorsrc:
--------------------------------------------------------------------------------
1 | {
2 | "projectName": "@dirkluijk/generic-material-table",
3 | "projectOwner": "dirkluijk",
4 | "repoType": "github",
5 | "repoHost": "https://github.com",
6 | "files": [
7 | "README.md"
8 | ],
9 | "imageSize": 100,
10 | "commit": true,
11 | "commitConvention": "angular",
12 | "contributors": [
13 | {
14 | "login": "dirkluijk",
15 | "name": "Dirk Luijk",
16 | "avatar_url": "https://avatars2.githubusercontent.com/u/2102973?v=4",
17 | "profile": "https://github.com/dirkluijk",
18 | "contributions": [
19 | "code",
20 | "doc"
21 | ]
22 | }
23 | ],
24 | "contributorsPerLine": 7
25 | }
26 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Editor configuration, see https://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | max_line_length = off
13 | trim_trailing_whitespace = false
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See http://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # compiled output
4 | /dist
5 | /tmp
6 | /out-tsc
7 | # Only exists if Bazel was run
8 | /bazel-out
9 |
10 | # dependencies
11 | /node_modules
12 |
13 | # profiling files
14 | chrome-profiler-events*.json
15 | speed-measure-plugin*.json
16 |
17 | # IDEs and editors
18 | /.idea
19 | .project
20 | .classpath
21 | .c9/
22 | *.launch
23 | .settings/
24 | *.sublime-workspace
25 |
26 | # IDE - VSCode
27 | .vscode/*
28 | !.vscode/settings.json
29 | !.vscode/tasks.json
30 | !.vscode/launch.json
31 | !.vscode/extensions.json
32 | .history/*
33 |
34 | # misc
35 | /.sass-cache
36 | /connect.lock
37 | /coverage
38 | /libpeerconnection.log
39 | npm-debug.log
40 | yarn-error.log
41 | testem.log
42 | /typings
43 |
44 | # System Files
45 | .DS_Store
46 | Thumbs.db
47 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 |
3 | cache:
4 | yarn: true
5 | directories:
6 | - node_modules
7 |
8 | node_js:
9 | - '10'
10 |
11 | script:
12 | - yarn lint
13 | - yarn build
14 | - yarn test
15 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4 |
5 | ## [0.2.0](https://github.com/dirkluijk/ngx-generic-material-tables/compare/v0.1.0...v0.2.0) (2019-09-25)
6 |
7 |
8 | ### Features
9 |
10 | * loading and reload functionality for reactive data sources ([#2](https://github.com/dirkluijk/ngx-generic-material-tables/issues/2)) ([a5fd0df](https://github.com/dirkluijk/ngx-generic-material-tables/commit/a5fd0df))
11 | * support for custom column filter predicates ([#3](https://github.com/dirkluijk/ngx-generic-material-tables/issues/3)) ([1d6b520](https://github.com/dirkluijk/ngx-generic-material-tables/commit/1d6b520))
12 |
13 | ## [0.1.0](https://github.com/dirkluijk/ngx-generic-material-tables/compare/v0.0.1...v0.1.0) (2019-08-16)
14 |
15 |
16 | ### ⚠ BREAKING CHANGES
17 |
18 | * changed the npm package name
19 |
20 | ### build
21 |
22 | * rename library ([1a4ee64](https://github.com/dirkluijk/ngx-generic-material-tables/commit/1a4ee64))
23 |
24 | ### 0.0.1 (2019-08-16)
25 |
26 |
27 | ### Features
28 |
29 | * add generic material table sorting and filtering utils ([46ae59f](https://github.com/dirkluijk/generic-material-tables/commit/46ae59f))
30 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Generic Angular Material Tables 🚀
2 |
3 | > Sorting and filtering utils to create generic Angular Material tables
4 |
5 | [](https://www.npmjs.com/package/@dirkluijk/ngx-generic-material-tables)
6 | [](https://www.npmjs.com/package/@dirkluijk/ngx-generic-material-tables)
7 | [](https://travis-ci.org/dirkluijk/ngx-generic-material-tables)
8 | [](#contributors-)
9 |
10 | ## Overview
11 |
12 | ### What? 🤔
13 |
14 | A small set of utils to make [Angular Material Tables](https://material.angular.io/components/table) more generic.
15 |
16 | * Sorting based on column names, with nested property support using dot notation
17 | * Filtering based on column names, with nested property support using dot notation
18 | * Sorts string values case-insensitive
19 | * Filter only on displayed columns (case-insensitive and trimming the filter string)
20 | * Persisted sorting using SessionStorage
21 | * Reactive data source for RxJS Observables
22 | * Reloading functionality (for reactive data sources)
23 |
24 | ### Why? 🤷♂️
25 |
26 | When using Angular Material Table, you may need more advanced sorting and filtering behaviour. That's why you usually end up with a lot of boilerplate code.
27 |
28 | This library provides some utils to use consistent sorting and filtering behaviour for all your tables.
29 |
30 | ## Installation 🌩
31 |
32 | ##### npm
33 |
34 | ```
35 | npm install @dirkluijk/ngx-generic-material-tables --save-dev
36 | ```
37 |
38 | ##### yarn
39 |
40 | ```
41 | yarn add @dirkluijk/ngx-generic-material-tables --dev
42 | ```
43 |
44 | ## Usage 🕹
45 |
46 | ### GenericTableDataSource
47 |
48 | The `GenericTableDataSource` allows you to use "dot notation" for your columns and benefit from the following features:
49 |
50 | * Only filter on the displayed columns (which you need to pass to it), using the dot notation
51 | * Use the sortable columns based on the values accessed using the dot notation
52 |
53 | ```typescript
54 | import { Component } from '@angular/core';
55 | import { GenericTableDataSource } from '@dirkluijk/ngx-generic-material-tables'
56 |
57 | @Component({
58 | template: `
59 |
60 |
61 | Name
62 |
63 | {{ row.name }}
64 |
65 |
66 |
67 |
68 | Foo Bar
69 |
70 | {{ row.foo.bar }}
71 | >
72 |
73 |
74 |
75 |
76 |
77 | `
78 | })
79 | export class MyComponent {
80 | public displayedColumns = ['name', 'foo.bar'];
81 | public genericDataSource = new GenericTableDataSource(this.displayedColumns, [/** your data */]);
82 | }
83 | ```
84 |
85 | ### Apply `MatSort` automatically
86 |
87 | Use the `gmtApplyMatSort` to automatically register the `MatSort` on the data source.
88 |
89 | ```html
90 |
93 | ```
94 |
95 | This allows you to leave out the following code:
96 |
97 | ```typescript
98 | ViewChild(MatSort, {static: true}) sort: MatSort; // not needed anymore!
99 |
100 | ngOnInit(): void {
101 | this.dataSource.sort = this.sort; // not needed anymore!
102 | }
103 | ```
104 |
105 | ### Persisted sorting
106 |
107 | You can persist the sorting actions to SessionStorage using the `gmtPersistedSort` directive.
108 | Just pass an additional identifier for your table in order to distinguish between multiple tables.
109 |
110 | ```html
111 |
114 | ```
115 |
116 | That's it!
117 |
118 | ### ReactiveGenericTableDataSource
119 |
120 | Even more awesome is the reactive version of the `GenericTableDataSource`:
121 |
122 | * Pass the displayed columns, table data and filter data as `Observable` stream
123 | * Automatically reacts to changes
124 | * Provides `reload()` functionality
125 | * Provides `loading`/`success`/`failed` static properties
126 | * Provides `loading$`/`success$`/`failed$` Observable properties
127 |
128 | ```typescript
129 | import { ReactiveGenericTableDataSource } from '@dirkluijk/ngx-generic-material-tables'
130 |
131 | const dataSource = new ReactiveGenericTableDataSource(
132 | displayedColumns$,
133 | yourTableData$,
134 | yourFilter$ // (optional)
135 | );
136 |
137 | dataSource.reload();
138 | ```
139 |
140 | ### Custom filtering for specific columns / types
141 |
142 | If you still want to have custom filtering for a specific column, filter value or column value,
143 | you can pass a `ColumnFilterPredicate`:
144 |
145 | ```typescript
146 | import { defaultColumnFilterPredicate } from '@dirkluijk/ngx-generic-material-tables';
147 |
148 | dataSource.columnFilterPredicate = (value, filter, columnName) => {
149 | // exact filter for this column
150 | if (columnName === 'vehicle.number') {
151 | return value.trim().includes(filter);
152 | }
153 |
154 | // custom filter for number values
155 | if (typeof value === 'number') {
156 | return String(yourFormatFn(value)).includes(filter);
157 | }
158 |
159 | return defaultColumnFilterPredicate(value, filter, columnName); // use default predicate for other cases
160 | };
161 | ```
162 |
163 | ## Contributors ✨
164 |
165 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
166 |
167 |
168 |
169 |
170 |
175 |
176 |
177 |
178 |
179 |
180 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
181 |
--------------------------------------------------------------------------------
/angular.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3 | "version": 1,
4 | "newProjectRoot": "projects",
5 | "projects": {
6 | "generic-material-tables": {
7 | "projectType": "library",
8 | "root": "projects/generic-material-tables",
9 | "sourceRoot": "projects/generic-material-tables/src",
10 | "prefix": "lib",
11 | "architect": {
12 | "build": {
13 | "builder": "@angular-devkit/build-ng-packagr:build",
14 | "options": {
15 | "tsConfig": "projects/generic-material-tables/tsconfig.lib.json",
16 | "project": "projects/generic-material-tables/ng-package.json"
17 | }
18 | },
19 | "lint": {
20 | "builder": "@angular-devkit/build-angular:tslint",
21 | "options": {
22 | "tsConfig": [
23 | "projects/generic-material-tables/tsconfig.lib.json"
24 | ],
25 | "exclude": [
26 | "**/node_modules/**"
27 | ]
28 | }
29 | }
30 | }
31 | },
32 | "demo": {
33 | "projectType": "application",
34 | "schematics": {
35 | "@schematics/angular:component": {
36 | "style": "scss"
37 | }
38 | },
39 | "root": "projects/demo",
40 | "sourceRoot": "projects/demo/src",
41 | "prefix": "app",
42 | "architect": {
43 | "build": {
44 | "builder": "@angular-devkit/build-angular:browser",
45 | "options": {
46 | "outputPath": "dist/demo",
47 | "index": "projects/demo/src/index.html",
48 | "main": "projects/demo/src/main.ts",
49 | "polyfills": "projects/demo/src/polyfills.ts",
50 | "tsConfig": "projects/demo/tsconfig.app.json",
51 | "aot": false,
52 | "assets": [
53 | "projects/demo/src/favicon.ico",
54 | "projects/demo/src/assets"
55 | ],
56 | "styles": [
57 | "projects/demo/src/styles.scss"
58 | ],
59 | "scripts": []
60 | },
61 | "configurations": {
62 | "production": {
63 | "fileReplacements": [
64 | {
65 | "replace": "projects/demo/src/environments/environment.ts",
66 | "with": "projects/demo/src/environments/environment.prod.ts"
67 | }
68 | ],
69 | "optimization": true,
70 | "outputHashing": "all",
71 | "sourceMap": false,
72 | "extractCss": true,
73 | "namedChunks": false,
74 | "aot": true,
75 | "extractLicenses": true,
76 | "vendorChunk": false,
77 | "buildOptimizer": true,
78 | "budgets": [
79 | {
80 | "type": "initial",
81 | "maximumWarning": "2mb",
82 | "maximumError": "5mb"
83 | },
84 | {
85 | "type": "anyComponentStyle",
86 | "maximumWarning": "6kb",
87 | "maximumError": "10kb"
88 | }
89 | ]
90 | }
91 | }
92 | },
93 | "serve": {
94 | "builder": "@angular-devkit/build-angular:dev-server",
95 | "options": {
96 | "browserTarget": "demo:build"
97 | },
98 | "configurations": {
99 | "production": {
100 | "browserTarget": "demo:build:production"
101 | }
102 | }
103 | },
104 | "extract-i18n": {
105 | "builder": "@angular-devkit/build-angular:extract-i18n",
106 | "options": {
107 | "browserTarget": "demo:build"
108 | }
109 | },
110 | "test": {
111 | "builder": "@angular-devkit/build-angular:karma",
112 | "options": {
113 | "main": "projects/demo/src/test.ts",
114 | "polyfills": "projects/demo/src/polyfills.ts",
115 | "tsConfig": "projects/demo/tsconfig.spec.json",
116 | "karmaConfig": "projects/demo/karma.conf.js",
117 | "assets": [
118 | "projects/demo/src/favicon.ico",
119 | "projects/demo/src/assets"
120 | ],
121 | "styles": [
122 | "projects/demo/src/styles.scss"
123 | ],
124 | "scripts": []
125 | }
126 | },
127 | "lint": {
128 | "builder": "@angular-devkit/build-angular:tslint",
129 | "options": {
130 | "tsConfig": [
131 | "projects/demo/tsconfig.app.json",
132 | "projects/demo/tsconfig.spec.json"
133 | ],
134 | "exclude": [
135 | "**/node_modules/**"
136 | ]
137 | }
138 | }
139 | }
140 | }},
141 | "defaultProject": "generic-material-tables"
142 | }
143 |
--------------------------------------------------------------------------------
/commitlint.config.js:
--------------------------------------------------------------------------------
1 | module.exports = { extends: ['@commitlint/config-conventional'] };
2 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@dirkluijk/ngx-generic-material-tables",
3 | "description": "Utils for generic Angular Material tables",
4 | "author": "Dirk Luijk ",
5 | "license": "MIT",
6 | "scripts": {
7 | "ng": "ng",
8 | "commit": "git-cz",
9 | "start": "ng serve demo",
10 | "build": "ng build && yarn copy:readme",
11 | "test": "ng test demo",
12 | "lint": "ng lint",
13 | "contributors:add": "all-contributors add",
14 | "contributors:generate": "all-contributors generate",
15 | "copy:readme": "cp README.md dist/generic-material-tables",
16 | "release": "cd projects/generic-material-tables && standard-version --infile ../../CHANGELOG.md && cd .. && yarn build"
17 | },
18 | "private": false,
19 | "dependencies": {
20 | "@angular/animations": "~8.2.0",
21 | "@angular/common": "~8.2.0",
22 | "@angular/compiler": "~8.2.0",
23 | "@angular/core": "~8.2.0",
24 | "@angular/forms": "~8.2.0",
25 | "@angular/platform-browser": "~8.2.0",
26 | "@angular/platform-browser-dynamic": "~8.2.0",
27 | "@angular/router": "~8.2.0",
28 | "rxjs": "~6.4.0",
29 | "tslib": "^1.10.0",
30 | "zone.js": "~0.9.1"
31 | },
32 | "peerDependencies": {
33 | "@angular/cdk": "^8.0.0",
34 | "@angular/material": "^8.0.0",
35 | "ngx-webstorage-service": "^4.0.0"
36 | },
37 | "devDependencies": {
38 | "@angular-devkit/build-angular": "~0.802.2",
39 | "@angular-devkit/build-ng-packagr": "~0.802.2",
40 | "@angular/cdk": "^8.1.3",
41 | "@angular/cli": "~8.2.0",
42 | "@angular/compiler-cli": "~8.2.0",
43 | "@angular/language-service": "~8.2.0",
44 | "@angular/material": "^8.1.3",
45 | "@commitlint/cli": "^8.1.0",
46 | "@commitlint/config-conventional": "^8.1.0",
47 | "@dirkluijk/observable-matchers": "^0.3.3",
48 | "@dscheerens/tslint-presets": "^6.0.0",
49 | "@ngneat/spectator": "^4.3.0",
50 | "@types/jasmine": "~3.3.8",
51 | "@types/jasminewd2": "~2.0.3",
52 | "@types/node": "~8.9.4",
53 | "all-contributors-cli": "^6.8.1",
54 | "codelyzer": "^5.0.0",
55 | "commitizen": "^4.0.3",
56 | "cz-conventional-changelog": "^3.0.2",
57 | "husky": "^3.0.3",
58 | "jasmine-core": "~3.4.0",
59 | "jasmine-spec-reporter": "~4.2.1",
60 | "karma": "~4.1.0",
61 | "karma-chrome-launcher": "~2.2.0",
62 | "karma-coverage-istanbul-reporter": "~2.0.1",
63 | "karma-jasmine": "~2.0.1",
64 | "karma-jasmine-html-reporter": "^1.4.0",
65 | "ng-packagr": "^5.3.0",
66 | "ngx-webstorage-service": "^4.0.1",
67 | "protractor": "~5.4.0",
68 | "standard-version": "^7.0.0",
69 | "ts-node": "~7.0.0",
70 | "tsickle": "^0.36.0",
71 | "tslint": "~5.15.0",
72 | "typescript": "~3.5.3"
73 | },
74 | "config": {
75 | "commitizen": {
76 | "path": "cz-conventional-changelog"
77 | }
78 | },
79 | "husky": {
80 | "hooks": {
81 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/projects/demo/browserslist:
--------------------------------------------------------------------------------
1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
2 | # For additional information regarding the format and rule options, please see:
3 | # https://github.com/browserslist/browserslist#queries
4 |
5 | # You can see what browsers were selected by your queries by running:
6 | # npx browserslist
7 |
8 | > 0.5%
9 | last 2 versions
10 | Firefox ESR
11 | not dead
12 | not IE 9-11 # For IE 9-11 support, remove 'not'.
--------------------------------------------------------------------------------
/projects/demo/karma.conf.js:
--------------------------------------------------------------------------------
1 | // Karma configuration file, see link for more information
2 | // https://karma-runner.github.io/1.0/config/configuration-file.html
3 |
4 | module.exports = function (config) {
5 | config.set({
6 | basePath: '',
7 | frameworks: ['jasmine', '@angular-devkit/build-angular'],
8 | plugins: [
9 | require('karma-jasmine'),
10 | require('karma-chrome-launcher'),
11 | require('karma-jasmine-html-reporter'),
12 | require('karma-coverage-istanbul-reporter'),
13 | require('@angular-devkit/build-angular/plugins/karma')
14 | ],
15 | client: {
16 | clearContext: false // leave Jasmine Spec Runner output visible in browser
17 | },
18 | coverageIstanbulReporter: {
19 | dir: require('path').join(__dirname, '../../coverage/demo'),
20 | reports: ['html', 'lcovonly', 'text-summary'],
21 | fixWebpackSourcePaths: true
22 | },
23 | reporters: ['progress', 'kjhtml'],
24 | port: 9876,
25 | colors: true,
26 | logLevel: config.LOG_INFO,
27 | autoWatch: true,
28 | browsers: ['ChromeHeadless'],
29 | singleRun: true,
30 | restartOnFileChange: true
31 | });
32 | };
33 |
--------------------------------------------------------------------------------
/projects/demo/src/app/app.component.spec.ts:
--------------------------------------------------------------------------------
1 | import {
2 | MatButtonModule,
3 | MatFormFieldModule,
4 | MatIconModule,
5 | MatInputModule,
6 | MatProgressSpinnerModule,
7 | MatTableModule
8 | } from '@angular/material';
9 | import { ReactiveFormsModule } from '@angular/forms';
10 | import { createComponentFactory, Spectator } from '@ngneat/spectator';
11 | import { SortModule } from '@dirkluijk/ngx-generic-material-tables';
12 | import { of } from 'rxjs';
13 | import { tap } from 'rxjs/operators';
14 | import { SESSION_STORAGE } from 'ngx-webstorage-service';
15 |
16 | import { AppComponent } from './app.component';
17 | import { Person, PersonService } from './person-service';
18 | import { ReactiveTableComponent } from './reactive-table/reactive-table.component';
19 | import { GenericTableComponent } from './generic-table/generic-table.component';
20 |
21 | describe('AppComponent', () => {
22 | let getDataSpy: jasmine.Spy;
23 |
24 | const createComponent = createComponentFactory({
25 | component: AppComponent,
26 | imports: [
27 | MatTableModule,
28 | SortModule,
29 | ReactiveFormsModule,
30 | MatProgressSpinnerModule,
31 | MatButtonModule,
32 | MatIconModule,
33 | MatFormFieldModule,
34 | MatInputModule
35 | ],
36 | declarations: [GenericTableComponent, ReactiveTableComponent],
37 | providers: [
38 | {
39 | provide: PersonService,
40 | useValue: {
41 | getPersons: () => of([
42 | {
43 | id: '1',
44 | name: 'John Doe',
45 | vehicle: {
46 | id: 'a',
47 | number: 'zz-yy-xx'
48 | },
49 | budget: 2000
50 | },
51 | {
52 | id: '2',
53 | name: 'Adam',
54 | vehicle: {
55 | id: 'c',
56 | number: 'yy-zz-xx'
57 | },
58 | budget: 2000
59 | },
60 | {
61 | id: '3',
62 | name: 'Other guy',
63 | vehicle: {
64 | id: 'b',
65 | number: 'aa-bb-cc'
66 | },
67 | budget: 4000
68 | }
69 | ]).pipe(tap(() => getDataSpy()))
70 | }
71 | }
72 | ]
73 | });
74 |
75 | let spectator: Spectator;
76 |
77 | beforeEach(() => {
78 | getDataSpy = jasmine.createSpy();
79 | spectator = createComponent();
80 | });
81 |
82 | afterEach(() => spectator.get(SESSION_STORAGE).clear());
83 |
84 | ['app-generic-table', 'app-reactive-table'].forEach((table) => {
85 | describe(table, () => {
86 | it('should sort all columns', () => {
87 | // id ascending
88 | spectator.click(spectator.query(`${ table } th.sort-id`, {root: true})!);
89 |
90 | expect(`${ table } tr:first-child td:nth-of-type(1)`).toHaveText('1');
91 | expect(`${ table } tr:first-child td:nth-of-type(2)`).toHaveText('John Doe');
92 | expect(`${ table } tr:first-child td:nth-of-type(3)`).toHaveText('zz-yy-xx');
93 |
94 | // id descending
95 | spectator.click(spectator.query(`${ table } th.sort-id`, {root: true})!);
96 |
97 | expect(`${ table } tr:first-child td:nth-of-type(1)`).toHaveText('3');
98 | expect(`${ table } tr:first-child td:nth-of-type(2)`).toHaveText('Other guy');
99 | expect(`${ table } tr:first-child td:nth-of-type(3)`).toHaveText('aa-bb-cc');
100 |
101 | // name ascending
102 | spectator.click(spectator.query(`${ table } th.sort-name`, {root: true})!);
103 |
104 | expect(`${ table } tr:first-child td:nth-of-type(1)`).toHaveText('2');
105 | expect(`${ table } tr:first-child td:nth-of-type(2)`).toHaveText('Adam');
106 | expect(`${ table } tr:first-child td:nth-of-type(3)`).toHaveText('yy-zz-xx');
107 |
108 | // name descending
109 | spectator.click(spectator.query(`${ table } th.sort-name`, {root: true})!);
110 |
111 | expect(`${ table } tr:first-child td:nth-of-type(1)`).toHaveText('3');
112 | expect(`${ table } tr:first-child td:nth-of-type(2)`).toHaveText('Other guy');
113 | expect(`${ table } tr:first-child td:nth-of-type(3)`).toHaveText('aa-bb-cc');
114 |
115 | // vehicle number ascending
116 | spectator.click(spectator.query(`${ table } th.sort-vehicle-nr`, {root: true})!);
117 |
118 | expect(`${ table } tr:first-child td:nth-of-type(1)`).toHaveText('3');
119 | expect(`${ table } tr:first-child td:nth-of-type(2)`).toHaveText('Other guy');
120 | expect(`${ table } tr:first-child td:nth-of-type(3)`).toHaveText('aa-bb-cc');
121 |
122 | // vehicle number descending
123 | spectator.click(spectator.query(`${ table } th.sort-vehicle-nr`, {root: true})!);
124 |
125 | expect(`${ table } tr:first-child td:nth-of-type(1)`).toHaveText('1');
126 | expect(`${ table } tr:first-child td:nth-of-type(2)`).toHaveText('John Doe');
127 | expect(`${ table } tr:first-child td:nth-of-type(3)`).toHaveText('zz-yy-xx');
128 | });
129 |
130 | it('should filter visible columns case-insensitive', () => {
131 | expect(`${ table } tr.row`).toHaveLength(3);
132 |
133 | spectator.typeInElement('a', `${ table } input`);
134 |
135 | expect(`${ table } tr:first-child td:nth-of-type(1)`).toHaveText('2');
136 | expect(`${ table } tr:first-child td:nth-of-type(2)`).toHaveText('Adam');
137 | expect(`${ table } tr:first-child td:nth-of-type(3)`).toHaveText('yy-zz-xx');
138 |
139 | expect(`${ table } tr.row`).toHaveLength(2);
140 |
141 | spectator.typeInElement('bb', `${ table } input`);
142 |
143 | expect(`${ table } tr:first-child td:nth-of-type(1)`).toHaveText('3');
144 | expect(`${ table } tr:first-child td:nth-of-type(2)`).toHaveText('Other guy');
145 | expect(`${ table } tr:first-child td:nth-of-type(3)`).toHaveText('aa-bb-cc');
146 |
147 | expect(`${ table } tr.row`).toHaveLength(1);
148 | });
149 | });
150 | });
151 |
152 | describe('app-generic-table', () => {
153 | it('should have reload functionality', () => {
154 | getDataSpy.calls.reset();
155 |
156 | spectator.click('button');
157 |
158 | expect(getDataSpy).toHaveBeenCalledTimes(1);
159 | });
160 | });
161 | });
162 |
--------------------------------------------------------------------------------
/projects/demo/src/app/app.component.ts:
--------------------------------------------------------------------------------
1 | import { ChangeDetectionStrategy, Component } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-root',
5 | template: `
6 | Generic Material tables
7 |
8 | Generic table data source (with custom filter predicate)
9 |
10 |
11 | Reactive table data source
12 |
13 | `,
14 | styles: [`
15 | h2 {
16 | margin-top: 1em;
17 | }
18 | `],
19 | changeDetection: ChangeDetectionStrategy.OnPush
20 | })
21 | export class AppComponent {}
22 |
--------------------------------------------------------------------------------
/projects/demo/src/app/app.module.ts:
--------------------------------------------------------------------------------
1 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
2 | import { NgModule } from '@angular/core';
3 | import { ReactiveFormsModule } from '@angular/forms';
4 | import {
5 | MatButtonModule,
6 | MatFormFieldModule,
7 | MatIconModule,
8 | MatInputModule,
9 | MatProgressSpinnerModule,
10 | MatTableModule
11 | } from '@angular/material';
12 | import { SortModule } from '@dirkluijk/ngx-generic-material-tables';
13 |
14 | import { AppComponent } from './app.component';
15 | import { GenericTableComponent } from './generic-table/generic-table.component';
16 | import { ReactiveTableComponent } from './reactive-table/reactive-table.component';
17 |
18 | @NgModule({
19 | declarations: [
20 | AppComponent,
21 | GenericTableComponent,
22 | ReactiveTableComponent
23 | ],
24 | imports: [
25 | BrowserAnimationsModule,
26 | MatTableModule,
27 | SortModule,
28 | ReactiveFormsModule,
29 | MatProgressSpinnerModule,
30 | MatButtonModule,
31 | MatIconModule,
32 | MatFormFieldModule,
33 | MatInputModule
34 | ],
35 | providers: [],
36 | bootstrap: [AppComponent]
37 | })
38 | export class AppModule { }
39 |
--------------------------------------------------------------------------------
/projects/demo/src/app/generic-table/generic-table.component.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | ID
8 |
9 | {{ person.id }}
10 |
11 |
12 |
13 | Name
14 |
15 | {{ person.name }}
16 |
17 |
18 |
19 | Vehicle number
20 |
21 | {{ person.vehicle.number }}
22 |
23 |
24 |
25 | Budget
26 |
27 | {{ person.budget | number }}
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/projects/demo/src/app/generic-table/generic-table.component.scss:
--------------------------------------------------------------------------------
1 | table {
2 | width: 100%;
3 | }
4 |
--------------------------------------------------------------------------------
/projects/demo/src/app/generic-table/generic-table.component.ts:
--------------------------------------------------------------------------------
1 | import { ChangeDetectionStrategy, Component, Inject, LOCALE_ID, OnInit } from '@angular/core';
2 | import { FormControl } from '@angular/forms';
3 | import { DecimalPipe } from '@angular/common';
4 | import { defaultColumnFilterPredicate, GenericTableDataSource } from '@dirkluijk/ngx-generic-material-tables';
5 |
6 | import { Person, PersonService } from '../person-service';
7 |
8 | @Component({
9 | selector: 'app-generic-table',
10 | templateUrl: './generic-table.component.html',
11 | styleUrls: ['./generic-table.component.scss'],
12 | changeDetection: ChangeDetectionStrategy.OnPush
13 | })
14 | export class GenericTableComponent implements OnInit {
15 | public readonly filterControl = new FormControl('');
16 |
17 | public readonly displayedColumns = ['id', 'name', 'vehicle.number', 'budget'];
18 | public readonly dataSource = new GenericTableDataSource(this.displayedColumns, []);
19 |
20 | constructor(private readonly personService: PersonService, @Inject(LOCALE_ID) private readonly locale: string) {}
21 |
22 | public ngOnInit(): void {
23 | this.personService.getPersons().subscribe((persons) => {
24 | this.dataSource.data = persons;
25 | });
26 |
27 | this.filterControl.valueChanges.subscribe((filterValue) => {
28 | return this.dataSource.filter = filterValue;
29 | });
30 |
31 | const decimalPipe = new DecimalPipe(this.locale);
32 |
33 | this.dataSource.columnFilterPredicate = (value, filter, columnName) => {
34 | if (columnName === 'vehicle.number') {
35 | return value.trim().includes(filter); // exact filter
36 | }
37 |
38 | if (typeof value === 'number') {
39 | return String(decimalPipe.transform(value)).includes(filter); // filter for decimal value;
40 | }
41 |
42 | return defaultColumnFilterPredicate(value, filter, columnName);
43 | };
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/projects/demo/src/app/person-service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 | import { Observable, of } from 'rxjs';
3 | import { delay, tap } from 'rxjs/operators';
4 |
5 | export interface Person {
6 | id: string;
7 | name: string;
8 | vehicle: {
9 | id: string;
10 | number: string;
11 | };
12 | budget: number;
13 | }
14 |
15 | @Injectable({ providedIn: 'root' })
16 | export class PersonService {
17 | public getPersons(): Observable {
18 | return of([
19 | {
20 | id: '1',
21 | name: 'John Doe',
22 | vehicle: {
23 | id: 'a',
24 | number: 'aa-bb-cc'
25 | },
26 | budget: 2000
27 | },
28 | {
29 | id: '2',
30 | name: 'Other guy',
31 | vehicle: {
32 | id: 'b',
33 | number: 'zz-yy-xx'
34 | },
35 | budget: 4000
36 | }
37 | ]).pipe(
38 | // tslint:disable-next-line:no-console
39 | tap(() => console.log('Getting persons...')),
40 | delay(400),
41 | );
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/projects/demo/src/app/reactive-table/reactive-table.component.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Reload
8 | Retry
9 |
10 |
11 | Error: {{ dataSource.error.message }}
12 |
13 |
14 |
15 | ID
16 |
17 | {{ person.id }}
18 |
19 |
20 |
21 | Name
22 |
23 | {{ person.name }}
24 |
25 |
26 |
27 | Vehicle number
28 |
29 | {{ person.vehicle.number }}
30 |
31 |
32 |
33 | Budget
34 |
35 | {{ person.budget | number }}
36 |
37 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/projects/demo/src/app/reactive-table/reactive-table.component.scss:
--------------------------------------------------------------------------------
1 | table {
2 | width: 100%;
3 | }
4 |
5 | mat-form-field {
6 | margin-right: 1em;
7 | }
8 |
9 | mat-spinner {
10 | width: 24px;
11 | height: 24px;
12 | }
13 |
--------------------------------------------------------------------------------
/projects/demo/src/app/reactive-table/reactive-table.component.ts:
--------------------------------------------------------------------------------
1 | import { ChangeDetectionStrategy, Component } from '@angular/core';
2 | import { FormControl } from '@angular/forms';
3 | import { ReactiveGenericTableDataSource } from '@dirkluijk/ngx-generic-material-tables';
4 | import { of } from 'rxjs';
5 |
6 | import { Person, PersonService } from '../person-service';
7 |
8 | @Component({
9 | selector: 'app-reactive-table',
10 | templateUrl: './reactive-table.component.html',
11 | styleUrls: ['./reactive-table.component.scss'],
12 | changeDetection: ChangeDetectionStrategy.OnPush
13 | })
14 | export class ReactiveTableComponent {
15 | public readonly filterControl = new FormControl('');
16 |
17 | public readonly displayedColumns = ['id', 'name', 'vehicle.number', 'budget'];
18 |
19 | public readonly dataSource = new ReactiveGenericTableDataSource(
20 | of(this.displayedColumns),
21 | this.personService.getPersons(),
22 | this.filterControl.valueChanges
23 | );
24 |
25 | constructor(private readonly personService: PersonService) {}
26 | }
27 |
--------------------------------------------------------------------------------
/projects/demo/src/assets/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dirkluijk/ngx-generic-material-tables/d506638eae4eb001a6a9211befaf51d0a1a557aa/projects/demo/src/assets/.gitkeep
--------------------------------------------------------------------------------
/projects/demo/src/environments/environment.prod.ts:
--------------------------------------------------------------------------------
1 | export const environment = {
2 | production: true
3 | };
4 |
--------------------------------------------------------------------------------
/projects/demo/src/environments/environment.ts:
--------------------------------------------------------------------------------
1 | // This file can be replaced during build by using the `fileReplacements` array.
2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
3 | // The list of file replacements can be found in `angular.json`.
4 |
5 | export const environment = {
6 | production: false
7 | };
8 |
9 | /*
10 | * For easier debugging in development mode, you can import the following file
11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
12 | *
13 | * This import should be commented out in production mode because it will have a negative impact
14 | * on performance if an error is thrown.
15 | */
16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI.
17 |
--------------------------------------------------------------------------------
/projects/demo/src/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dirkluijk/ngx-generic-material-tables/d506638eae4eb001a6a9211befaf51d0a1a557aa/projects/demo/src/favicon.ico
--------------------------------------------------------------------------------
/projects/demo/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Demo
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/projects/demo/src/main.ts:
--------------------------------------------------------------------------------
1 | import { enableProdMode } from '@angular/core';
2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
3 |
4 | import { AppModule } from './app/app.module';
5 | import { environment } from './environments/environment';
6 |
7 | if (environment.production) {
8 | enableProdMode();
9 | }
10 |
11 | platformBrowserDynamic().bootstrapModule(AppModule)
12 | .catch((err) => {
13 | // tslint:disable-next-line:no-console
14 | console.error(err);
15 | });
16 |
--------------------------------------------------------------------------------
/projects/demo/src/polyfills.ts:
--------------------------------------------------------------------------------
1 | // tslint:disable
2 | /**
3 | * This file includes polyfills needed by Angular and is loaded before the app.
4 | * You can add your own extra polyfills to this file.
5 | *
6 | * This file is divided into 2 sections:
7 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
8 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main
9 | * file.
10 | *
11 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
12 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
13 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
14 | *
15 | * Learn more in https://angular.io/guide/browser-support
16 | */
17 |
18 | /***************************************************************************************************
19 | * BROWSER POLYFILLS
20 | */
21 |
22 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */
23 | // import 'classlist.js'; // Run `npm install --save classlist.js`.
24 |
25 | /**
26 | * Web Animations `@angular/platform-browser/animations`
27 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
28 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
29 | */
30 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`.
31 |
32 | /**
33 | * By default, zone.js will patch all possible macroTask and DomEvents
34 | * user can disable parts of macroTask/DomEvents patch by setting following flags
35 | * because those flags need to be set before `zone.js` being loaded, and webpack
36 | * will put import in the top of bundle, so user need to create a separate file
37 | * in this directory (for example: zone-flags.ts), and put the following flags
38 | * into that file, and then add the following code before importing zone.js.
39 | * import './zone-flags.ts';
40 | *
41 | * The flags allowed in zone-flags.ts are listed here.
42 | *
43 | * The following flags will work for all browsers.
44 | *
45 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
46 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
47 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
48 | *
49 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
50 | * with the following flag, it will bypass `zone.js` patch for IE/Edge
51 | *
52 | * (window as any).__Zone_enable_cross_context_check = true;
53 | *
54 | */
55 |
56 | /***************************************************************************************************
57 | * Zone JS is required by default for Angular itself.
58 | */
59 | import 'zone.js/dist/zone'; // Included with Angular CLI.
60 |
61 |
62 | /***************************************************************************************************
63 | * APPLICATION IMPORTS
64 | */
65 |
--------------------------------------------------------------------------------
/projects/demo/src/styles.scss:
--------------------------------------------------------------------------------
1 | @import "~@angular/material/prebuilt-themes/indigo-pink.css";
2 |
--------------------------------------------------------------------------------
/projects/demo/src/test.ts:
--------------------------------------------------------------------------------
1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
2 | // tslint:disable
3 |
4 | import 'zone.js/dist/zone-testing';
5 | import { getTestBed } from '@angular/core/testing';
6 | import {
7 | BrowserDynamicTestingModule,
8 | platformBrowserDynamicTesting
9 | } from '@angular/platform-browser-dynamic/testing';
10 |
11 | declare const require: any;
12 |
13 | // First, initialize the Angular testing environment.
14 | getTestBed().initTestEnvironment(
15 | BrowserDynamicTestingModule,
16 | platformBrowserDynamicTesting()
17 | );
18 | // Then we find all the tests.
19 | const context = require.context('./', true, /\.spec\.ts$/);
20 | // And load the modules.
21 | context.keys().map(context);
22 |
--------------------------------------------------------------------------------
/projects/demo/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../../out-tsc/app",
5 | "types": [],
6 | "paths": {
7 | "@dirkluijk/ngx-generic-material-tables": [
8 | "projects/generic-material-tables/src/public-api.ts"
9 | ]
10 | }
11 | },
12 | "files": [
13 | "src/main.ts",
14 | "src/polyfills.ts"
15 | ],
16 | "include": [
17 | "src/**/*.ts"
18 | ],
19 | "exclude": [
20 | "src/test.ts",
21 | "src/**/*.spec.ts"
22 | ]
23 | }
24 |
--------------------------------------------------------------------------------
/projects/demo/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../../out-tsc/spec",
5 | "types": [
6 | "jasmine",
7 | "node"
8 | ],
9 | "paths": {
10 | "@dirkluijk/ngx-generic-material-tables": [
11 | "projects/generic-material-tables/src/public-api.ts"
12 | ]
13 | }
14 | },
15 | "files": [
16 | "src/test.ts",
17 | "src/polyfills.ts"
18 | ],
19 | "include": [
20 | "src/**/*.spec.ts",
21 | "src/**/*.d.ts"
22 | ]
23 | }
24 |
--------------------------------------------------------------------------------
/projects/demo/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tslint.json",
3 | "rules": {
4 | "directive-selector": [
5 | true,
6 | "attribute",
7 | "app",
8 | "camelCase"
9 | ],
10 | "component-selector": [
11 | true,
12 | "element",
13 | "app",
14 | "kebab-case"
15 | ]
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/README.md:
--------------------------------------------------------------------------------
1 | # GenericMaterialTable
2 |
3 | This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.2.0.
4 |
5 | ## Code scaffolding
6 |
7 | Run `ng generate component component-name --project generic-material-table` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module --project generic-material-table`.
8 | > Note: Don't forget to add `--project generic-material-table` or else it will be added to the default project in your `angular.json` file.
9 |
10 | ## Build
11 |
12 | Run `ng build generic-material-table` to build the project. The build artifacts will be stored in the `dist/` directory.
13 |
14 | ## Publishing
15 |
16 | After building your library with `ng build generic-material-table`, go to the dist folder `cd dist/generic-material-table` and run `npm publish`.
17 |
18 | ## Running unit tests
19 |
20 | Run `ng test generic-material-table` to execute the unit tests via [Karma](https://karma-runner.github.io).
21 |
22 | ## Further help
23 |
24 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
25 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/ng-package.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
3 | "dest": "../../dist/generic-material-tables",
4 | "lib": {
5 | "entryFile": "src/public-api.ts"
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@dirkluijk/ngx-generic-material-tables",
3 | "version": "0.2.0",
4 | "description": "Utils for generic Angular Material tables",
5 | "author": "Dirk Luijk ",
6 | "license": "MIT",
7 | "private": false,
8 | "peerDependencies": {
9 | "@angular/cdk": "^8.0.0",
10 | "@angular/material": "^8.0.0",
11 | "ngx-webstorage-service": "^4.0.0"
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/data-source/generic-table-data-source.ts:
--------------------------------------------------------------------------------
1 | import { MatTableDataSource } from '@angular/material';
2 |
3 | import { createGenericFilterPredicate } from '../filtering/generic-filter-predicate.fn';
4 | import { genericSortingAccessor } from '../sorting/generic-sorting-accessor.fn';
5 | import { ColumnFilterPredicate } from '../filtering/column-filter-predicate';
6 | import { defaultColumnFilterPredicate } from '../filtering/default-column-filter-predicate';
7 |
8 | /**
9 | * A MatTableDataSource which has generic sorting and filtering behaviour. It assumes the column names to match the data
10 | * properties, with support for dot notation.
11 | */
12 | export class GenericTableDataSource extends MatTableDataSource {
13 | public set columnFilterPredicate(columnPredicate: ColumnFilterPredicate) {
14 | this._columnPredicate = columnPredicate;
15 | this.updateFilterPredicate();
16 | }
17 |
18 | public set filterColumns(columns: Iterable) {
19 | this._filterColumns = columns;
20 | this.updateFilterPredicate();
21 | }
22 |
23 | private _filterColumns: Iterable = [];
24 | private _columnPredicate: ColumnFilterPredicate = defaultColumnFilterPredicate;
25 |
26 | constructor(filterColumns: Iterable, initialData?: T[]) {
27 | super(initialData);
28 |
29 | this.sortingDataAccessor = genericSortingAccessor;
30 | this.filterColumns = filterColumns;
31 | }
32 |
33 | private updateFilterPredicate(): void {
34 | this.filterPredicate = createGenericFilterPredicate(this._filterColumns, this._columnPredicate);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/data-source/reactive-generic-table-data-source.ts:
--------------------------------------------------------------------------------
1 | import { BehaviorSubject, Observable, Subscription } from 'rxjs';
2 | import { map, shareReplay, switchMap } from 'rxjs/operators';
3 |
4 | import { mapToLoadable } from '../internals/loading/map-to-loadable.operator';
5 | import { Loadable } from '../internals/loading/loadable';
6 |
7 | import { GenericTableDataSource } from './generic-table-data-source';
8 |
9 | /**
10 | * A reactive version of GenericTableDataSource, for which a stream of data can be passed.
11 | */
12 | export class ReactiveGenericTableDataSource extends GenericTableDataSource {
13 | public loading = false;
14 | public success = false;
15 | public failed = false;
16 |
17 | public readonly loading$: Observable;
18 | public readonly success$: Observable;
19 | public readonly failed$: Observable;
20 |
21 | public error?: Error;
22 |
23 | private readonly subscription = new Subscription();
24 | private readonly reloadSubject = new BehaviorSubject(undefined);
25 | private readonly loadableData$: Observable>;
26 |
27 | constructor(
28 | private readonly filterColumns$: Observable>,
29 | private readonly data$: Observable,
30 | private readonly filter$?: Observable
31 | ) {
32 | super([], []);
33 |
34 | this.loadableData$ = this.reloadSubject.pipe(
35 | switchMap(() => this.data$.pipe(mapToLoadable())),
36 | shareReplay()
37 | );
38 |
39 | this.loading$ = this.loadableData$.pipe(map((l) => l.loading));
40 | this.success$ = this.loadableData$.pipe(map((l) => l.success));
41 | this.failed$ = this.loadableData$.pipe(map((l) => l.failed));
42 | }
43 |
44 | public connect(): BehaviorSubject {
45 | this.subscription.add(
46 | this.loadableData$.subscribe((loadable) => {
47 | this.loading = loadable.loading;
48 | this.success = loadable.success;
49 | this.failed = loadable.failed;
50 |
51 | if (loadable.failed) {
52 | this.error = loadable.error;
53 | this.data = [];
54 | } else if (loadable.success) {
55 | this.error = undefined;
56 | this.data = loadable.value;
57 | }
58 | }));
59 |
60 | this.subscription.add(this.filterColumns$.subscribe((columns) => this.filterColumns = columns));
61 |
62 | if (this.filter$) {
63 | this.subscription.add(this.filter$.subscribe((filter) => this.filter = filter));
64 | }
65 |
66 | return super.connect();
67 | }
68 |
69 | public disconnect(): void {
70 | super.disconnect();
71 |
72 | this.subscription.unsubscribe();
73 | }
74 |
75 | public reload(): void {
76 | this.reloadSubject.next();
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/filtering/column-filter-predicate.ts:
--------------------------------------------------------------------------------
1 | export type ColumnFilterPredicate = (value: any, filter: string, columnName: string) => boolean;
2 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/filtering/data-source-filter-predicate.ts:
--------------------------------------------------------------------------------
1 | export type DataSourceFilterPredicate = (data: T, filter: string) => boolean;
2 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/filtering/default-column-filter-predicate.ts:
--------------------------------------------------------------------------------
1 | import { ColumnFilterPredicate } from './column-filter-predicate';
2 |
3 | /**
4 | * A default filter predicate function for columns in a data source.
5 | */
6 | export const defaultColumnFilterPredicate: ColumnFilterPredicate = (value: any, filter: string): boolean => {
7 | return value !== undefined && String(value).trim().toLocaleLowerCase().includes(filter.toLocaleLowerCase());
8 | };
9 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/filtering/generic-filter-predicate.fn.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Creates a filter predicate function for a MatTableDataSource, which supports deep properties (dot notation) and
3 | * only filters on the displayed columns.
4 | */
5 | import { readProperty } from '../internals/read-property.fn';
6 |
7 | import { defaultColumnFilterPredicate } from './default-column-filter-predicate';
8 | import { DataSourceFilterPredicate } from './data-source-filter-predicate';
9 | import { ColumnFilterPredicate } from './column-filter-predicate';
10 |
11 | export function createGenericFilterPredicate(
12 | columns: Iterable,
13 | filterColumn: ColumnFilterPredicate = defaultColumnFilterPredicate
14 | ): DataSourceFilterPredicate {
15 | return (data: T, filter: string): boolean => {
16 | return Array.from(columns).some((columnName) => {
17 | const value = readProperty(data, columnName);
18 |
19 | return filterColumn(value, filter, columnName);
20 | });
21 | };
22 | }
23 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/internals/loading/loadable.ts:
--------------------------------------------------------------------------------
1 | export interface Loading {
2 | loading: true;
3 | failed: false;
4 | success: false;
5 | }
6 |
7 | export interface Failed {
8 | loading: false;
9 | failed: true;
10 | success: false;
11 | error: E;
12 | }
13 |
14 | export interface Success {
15 | loading: false;
16 | failed: false;
17 | success: true;
18 | value: T;
19 | }
20 |
21 | export type Loadable = Readonly<(Loading | Failed | Success)>;
22 |
23 | export function loading(): Loading {
24 | return { loading: true, failed: false, success: false };
25 | }
26 |
27 | export function success(value: T): Success {
28 | return { loading: false, failed: false, success: true, value };
29 | }
30 |
31 | export function failed(error: E): Failed {
32 | return { loading: false, failed: true, success: false, error };
33 | }
34 |
35 | export const LOADING = loading();
36 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/internals/loading/map-to-loadable.operator.spec.ts:
--------------------------------------------------------------------------------
1 | import { discardPeriodicTasks, fakeAsync, tick } from '@angular/core/testing';
2 | import { of, throwError } from 'rxjs';
3 | import { delay } from 'rxjs/operators';
4 | import { completed, next, observable, record } from '@dirkluijk/observable-matchers';
5 |
6 | import { mapToLoadable } from './map-to-loadable.operator';
7 | import { Loadable, loading, success, failed } from './loadable';
8 |
9 | describe('MapToLoadable operator', () => {
10 | it('should be loading initially', fakeAsync(() => {
11 | const foo$ = of('foo').pipe(
12 | delay(1000),
13 | mapToLoadable()
14 | );
15 |
16 | expect(foo$).toEqual(observable(
17 | next(loading())
18 | ));
19 |
20 | discardPeriodicTasks();
21 | }));
22 |
23 | it('should be success on emit', fakeAsync(() => {
24 | const foo$ = of('foo').pipe(
25 | delay(1000),
26 | mapToLoadable()
27 | );
28 |
29 | const recorded$ = record(foo$);
30 |
31 | tick(1000);
32 |
33 | expect(recorded$).toEqual(observable>(
34 | next(loading()),
35 | next(success('foo')),
36 | completed()
37 | ));
38 | }));
39 |
40 | it('should be failed on emit', fakeAsync(() => {
41 | const foo$ = throwError('error').pipe(
42 | delay(1000),
43 | mapToLoadable()
44 | );
45 |
46 | const recorded$ = record(foo$);
47 |
48 | tick(1000);
49 |
50 | expect(recorded$).toEqual(observable>(
51 | next(loading()),
52 | next(failed('error')),
53 | completed()
54 | ));
55 | }));
56 | });
57 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/internals/loading/map-to-loadable.operator.ts:
--------------------------------------------------------------------------------
1 | import { concat, Observable, of, OperatorFunction } from 'rxjs';
2 | import { catchError, map } from 'rxjs/operators';
3 |
4 | import { failed, Loadable, LOADING, success } from './loadable';
5 |
6 | export function mapToLoadable(): OperatorFunction> {
7 | return (source$: Observable) => concat>(
8 | of(LOADING),
9 | source$.pipe(
10 | map((value) => success(value)),
11 | catchError((error: E) => of(failed(error)))
12 | )
13 | );
14 | }
15 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/internals/read-property.fn.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Simple accessor function which can be used to retrieve properties from a record using a dot notation.
3 | */
4 | export function readProperty(object: { [key: string]: any }, path: string): any | undefined {
5 | try {
6 | return path.split('.').reduce((a, b) => a[b], object);
7 | } catch {
8 | return undefined;
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/sorting/apply-mat-sort.directive.ts:
--------------------------------------------------------------------------------
1 | import { Directive, Host, OnInit } from '@angular/core';
2 | import { MatSort, MatTable, MatTableDataSource } from '@angular/material';
3 |
4 | /**
5 | * Directives which automatically registers a MatSort to a MatTableDataSource.
6 | */
7 | @Directive({
8 | selector: '[gmtApplyMatSort]'
9 | })
10 | export class ApplyMatSortDirective implements OnInit {
11 | constructor(@Host() private readonly matTable: MatTable, @Host() private readonly matSort: MatSort) {}
12 |
13 | public ngOnInit(): void {
14 | if (this.matTable.dataSource instanceof MatTableDataSource) {
15 | this.matTable.dataSource.sort = this.matSort;
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/sorting/generic-sorting-accessor.fn.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Simple sorting accessor function for MatTableDataSource, which supports deep properties (dot notation) and
3 | * case insensitive sorting.
4 | *
5 | * Ripped from https://github.com/angular/components/issues/9205#issuecomment-387326580.
6 | */
7 | import { readProperty } from '../internals/read-property.fn';
8 |
9 | export function genericSortingAccessor(data: T, sortHeaderId: string): string | number {
10 | const value = readProperty(data, sortHeaderId);
11 |
12 | if (typeof value === 'string') {
13 | return value.toLocaleLowerCase();
14 | }
15 |
16 | return value || '';
17 | }
18 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/sorting/persisted-sort.directive.ts:
--------------------------------------------------------------------------------
1 | import { Directive, Host, Inject, Input, OnDestroy, OnInit } from '@angular/core';
2 | import { MatSort, Sort } from '@angular/material';
3 | import { SESSION_STORAGE, StorageService } from 'ngx-webstorage-service';
4 | import { Subscription } from 'rxjs';
5 |
6 | /**
7 | * Directives which persists the sort of MatSort in StorageService.
8 | */
9 | @Directive({
10 | selector: '[gmtPersistedSort]'
11 | })
12 | export class PersistedSortDirective implements OnInit, OnDestroy {
13 | @Input('gmtPersistedSort') public key!: string;
14 |
15 | private readonly sortChangeSubscription = new Subscription();
16 |
17 | constructor(
18 | @Host() private readonly matSort: MatSort,
19 | @Inject(SESSION_STORAGE) private readonly storage: StorageService
20 | ) {}
21 |
22 | public ngOnInit(): void {
23 | this.restoreSort();
24 |
25 | this.sortChangeSubscription.add(
26 | this.matSort.sortChange.subscribe((sort: Sort) => this.saveSort(sort))
27 | );
28 | }
29 |
30 | public ngOnDestroy(): void {
31 | this.sortChangeSubscription.unsubscribe();
32 | }
33 |
34 | private saveSort(sort: Sort): void {
35 | this.storage.set(this.fullStorageKey, sort);
36 | }
37 |
38 | private restoreSort(): void {
39 | const currentSort = this.storage.get(this.fullStorageKey);
40 |
41 | if (currentSort) {
42 | this.matSort.active = currentSort.active;
43 | this.matSort.direction = currentSort.direction;
44 | this.matSort._stateChanges.next();
45 | }
46 | }
47 |
48 | private get fullStorageKey(): string {
49 | return `persisted.sort.${ this.key }`;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/lib/sorting/sort.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { MatSortModule } from '@angular/material';
3 |
4 | import { ApplyMatSortDirective } from './apply-mat-sort.directive';
5 | import { PersistedSortDirective } from './persisted-sort.directive';
6 |
7 | @NgModule({
8 | declarations: [ApplyMatSortDirective, PersistedSortDirective],
9 | exports: [ApplyMatSortDirective, PersistedSortDirective, MatSortModule]
10 | })
11 | export class SortModule {}
12 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/src/public-api.ts:
--------------------------------------------------------------------------------
1 | export * from './lib/data-source/generic-table-data-source';
2 | export * from './lib/data-source/reactive-generic-table-data-source';
3 | export * from './lib/filtering/generic-filter-predicate.fn';
4 | export * from './lib/filtering/column-filter-predicate';
5 | export * from './lib/filtering/data-source-filter-predicate';
6 | export * from './lib/filtering/default-column-filter-predicate';
7 | export * from './lib/sorting/persisted-sort.directive';
8 | export * from './lib/sorting/apply-mat-sort.directive';
9 | export * from './lib/sorting/generic-sorting-accessor.fn';
10 | export * from './lib/sorting/sort.module';
11 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/tsconfig.lib.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../../out-tsc/lib",
5 | "target": "es2015",
6 | "declaration": true,
7 | "inlineSources": true,
8 | "types": [],
9 | "lib": [
10 | "dom",
11 | "es2018"
12 | ]
13 | },
14 | "angularCompilerOptions": {
15 | "annotateForClosureCompiler": true,
16 | "skipTemplateCodegen": true,
17 | "strictMetadataEmit": true,
18 | "fullTemplateTypeCheck": true,
19 | "strictInjectionParameters": true,
20 | "enableResourceInlining": true
21 | },
22 | "exclude": [
23 | "src/test.ts",
24 | "**/*.spec.ts"
25 | ]
26 | }
27 |
--------------------------------------------------------------------------------
/projects/generic-material-tables/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tslint.json",
3 | "rules": {
4 | "directive-selector": [
5 | true,
6 | "attribute",
7 | "gmt",
8 | "camelCase"
9 | ],
10 | "component-selector": [
11 | true,
12 | "element",
13 | "gmt",
14 | "kebab-case"
15 | ]
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compileOnSave": false,
3 | "compilerOptions": {
4 | "baseUrl": "./",
5 | "outDir": "./dist/out-tsc",
6 | "strict": true,
7 | "noImplicitAny": true,
8 | "strictNullChecks": true,
9 | "strictFunctionTypes": true,
10 | "strictBindCallApply": true,
11 | "strictPropertyInitialization": true,
12 | "noImplicitThis": true,
13 | "alwaysStrict": true,
14 | "noUnusedLocals": true,
15 | "noUnusedParameters": true,
16 | "noImplicitReturns": true,
17 | "noFallthroughCasesInSwitch": true,
18 | "sourceMap": true,
19 | "declaration": false,
20 | "downlevelIteration": true,
21 | "experimentalDecorators": true,
22 | "module": "esnext",
23 | "moduleResolution": "node",
24 | "importHelpers": true,
25 | "target": "es2015",
26 | "typeRoots": [
27 | "node_modules/@types"
28 | ],
29 | "lib": [
30 | "es2018",
31 | "dom"
32 | ]
33 | },
34 | "angularCompilerOptions": {
35 | "fullTemplateTypeCheck": true,
36 | "strictInjectionParameters": true
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "@dscheerens/tslint-presets/tslint.recommended.angular.json",
3 | "rules": {
4 | "linebreak-style": false,
5 | "no-implicit-dependencies": false,
6 | "strict-indent-size": [true, 2],
7 | "variable-name": [
8 | true,
9 | "check-format",
10 | "allow-pascal-case",
11 | "ban-keywords",
12 | "allow-leading-underscore"
13 | ]
14 | }
15 | }
16 |
--------------------------------------------------------------------------------