Giter Site home page Giter Site logo

valor-software / ng2-table Goto Github PK

View Code? Open in Web Editor NEW
554.0 41.0 337.0 16.19 MB

Simple table extension with sorting, filtering, paging... for Angular2 apps

Home Page: http://valor-software.github.io/ng2-table/

License: MIT License

TypeScript 52.30% CSS 30.71% HTML 5.08% JavaScript 11.92%

ng2-table's Introduction

ng2-table npm version

Simple table extension with sorting, filtering, paging... for Angular2 apps

Follow me twitter to be notified about new releases.

Angular 2 Style Guide Build Status Code Climate Join the chat at https://gitter.im/valor-software/ng2-bootstrap Dependency Status devDependency Status Throughput Graph

Usage & Demo

http://valor-software.github.io/ng2-table/


Installation

  1. A recommended way to install ng2-table is through npm package manager using the following command:
npm i ng2-table --save

Alternatively, you can download it in a ZIP file.

  1. More information regarding using of ng2-table is located in demo and demo sources.

Documentation

Inputs (Properties)

  • page (number) - the default page after the table component loading

  • itemsPerPage (number) - number of the displaying items (rows) on a page

  • maxSize (number) - number of the displaying pages before ...

  • numPages (number) - total number of the pages

  • length (number) - total number of the items after filtering (of it's chosen)

  • config (?any) - config for setup all plugins (filtering, sorting, paging):

    • paging (?boolean) - - switch on the paging plugin
    • sorting (?any) - switch on the sorting plugin
      • columns (Array<any>) - only list of the columns for sorting
    • filtering (?any) - switch on the filtering plugin
      • filterString (string) - the default value for filter
      • columnName (string) - the property name in raw data
    • className (string|Array<string>) - additional CSS classes that should be added to a
    • rows (?Array<any>) - only list of the rows which should be displayed

    • columns (?Array<any>) - config for columns (+ sorting settings if it's needed)

      • title (string) - the title of column header
      • name (string) - the property name in data
      • sort (?string|boolean) - config for columns (+ sorting settings if it's needed), sorting is switched on by default for each column
      • className (string|Array<string>) - additional CSS classes that should be added to a column header
      • filtering (?any) - switch on the filtering plugin
        • filterString (string) - the default value for filter
        • columnName (string) - the property name in raw data
    • Outputs (Events)

      • tableChanged: data change event handler
      • cellClicked: onclick event handler

      Filter

      The responsibility of the filtering issue falls on user. You should choose on which columns the filter would be applied. You could add any number of different filters. Filter string - it's a string for matching values in raw data. Column name refers to the property name in raw data. The rest logic you could organize by yourself (the order of filters, data formats, etc). Even you could use filter for list of data columns.

      You can also set up filtering param for columns, in this case filter box will appear in first row of the table.

      Sorting

      Data sorting could be in 3 modes: asc, desc and without sorting data (as it comes from backend or somewhere else). If you want to switch off the sorting for some of the columns then you should set it forcibly in columns config (set property sort to false value for each column you want)

      Paging

      Pagination could be used from ng2-bootstrap - pagination component. When the page is changed, the pagination component will emit event change-table with an object {page, itemsPerPage}. Then you can easily subscribe on it and request corresponding raw data.

      Troubleshooting

      Please follow this guidelines when reporting bugs and feature requests:

      1. Use GitHub Issues board to report bugs and feature requests (not our email address)
      2. Please always write steps to reproduce the error. That way we can focus on fixing the bug, not scratching our heads trying to reproduce it.

      Thanks for understanding!

      License

      The MIT License (see the LICENSE file for the full text)

ng2-table's People

Contributors

buchslava avatar dtchau avatar greenkeeperio-bot avatar jdelgadoalfonso avatar joepurdy avatar korel-san avatar nimmard avatar otelnov avatar shahmirn avatar valorkin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ng2-table's Issues

FEATURE: Allow access to properties that are deeper down the object tree

Hi everyone,

The current implementation only allows the user to access a row's first-level properties.

For example, if you have some underlying objects that look like this

let students = [
  {name: 'ABC', address: {number: 123, street: ABC Street'}, phones: [{type: 'cell', number: 123456789}]},
  {name: 'XYZ', address: {number: 456, street: 'XYZ Street'}, phones: [{type: 'cell', number: 123456789}]}
];

and you want to display the street on the table, you will first have to map them to something like this

let rows = students.map(student => {
  return {name: student.name, addressNumber: student.address.number, addressStreet: student.address.street};
})

before you can assign this to ngTable's rows input. It's because rows[0]['address.number'] will return undefined.

I propose we allow users to access properties that are deeper than the first-level properties.

For example, to display the street name, one can simply set the column.name to 'address.street'. This notation will work for array too. For example, to show the first phone number, just set column.name to 'phones.0.number'.

I need this for myself so I made a change and sent in a PR. Please take a look and let me know what you think.

Thank you.

ng2-table.js:4Uncaught ReferenceError: require is not defined

This is where it stopped in ng2-table.js. Thanks in advance!

__export(require('./components/table/ng-table.component'));
__export(require('./components/table/ng-table-filtering.directive'));
__export(require('./components/table/ng-table-paging.directive'));
__export(require('./components/table/ng-table-sorting.directive'));
__export(require('./components/ng-table-directives'));

New Column

How can I add a new column with button that show the details of the row ????

Issue feature disable sort of table

Hi guy,

my table have two column: id can sort, name can't sort

public columns:Array = [
{title: 'Id', name: 'id'},
{title: 'Name', name: 'name', sort: false}
];

When run function onChangeTable excute, parameter config is:

[
{name: "id", title: "Id"},
{name: "name", title: "Name", sort: false}
]

I click column "id" to sort. Now, column "name" can sort => Issue. I checked function onChangeTable excute, parameter config is:

[
{name: "id", title: "Id", sort: "asc"},
{name: "name", title: "Name", sort: ""}
]

Sorting issue

There is a issue in sorting when navigating to descending. The issue is in the file
ng2-table/components/table/ng-table-sorting.directive.ts
line 28: this.column.sort = '';

It works when its changed to this.column.sort = 'asc';
Can this fix be added soon.

Sasi

sort per column

need the ability to have column header fire event on click and return the corresponding sort order so we can sort data per column.
Please add this feature as it is so common and it will definitely make ng2-table useful.

Table pagination

There is a bug. steps to replicate:

  1. Change page on pagination, lets say page 3.
  2. filter value in input box.

Table is stuck on page 3 with no records.

Does not compile: any type?

I just tried to use the latest version and it doesn't compile:

client/node_modules/ng2-table/components/table/ng-table.component.ts(42,34): error TS2339: Property 'find' does not exist on type 'any[]'.
client/node_modules/ng2-table/components/table/ng-table.component.ts(42,40): error TS7006: Parameter 'col' implicitly has an 'any' type.
client/node_modules/ng2-table/components/table/ng-table.component.ts(44,16): error TS2339: Property 'assign' does not exist on type 'ObjectConstructor'.

Am I missing something?

Sort in demo

Hi,

I was trying the sort feature in demo app.

I think that there is a bug in table-demo.html.

change

<ngTable [config]="config.sorting" (tableChanged)="onChangeTable(config)" [rows]="rows" [columns]="columns">

by

`<ngTable [config]="config.sorting"
(tableChanged)="onChangeTable($event)"
[rows]="rows" [columns]="columns">

Is this correct?

Thanks.

Event on table item click

Hi,

thanks for nice table. We want to use it in our project but we need events on table item click, do you plan to add this feature?

Lukas

404 error

import {NG_TABLE_DIRECTIVES} from 'ng2-table';

image

add class to <table> in ng2-table

Hello

How can I pass the class

in the component.
I want to hang their styles through the class .
whether it is possible to implement it in the current version ?

How to dynamically load data

Was wondering if you had an example loading data from an api endpoint? I haven't been able to get dynamically fetched data to show up in the table, only if I hard-code the values in-memory.

[Improvement] New markup proposal

Hi guys,

I tried to use the component, and it seems a bit rigid, so I've implemented a more flexible version of the table.

A short chagelist:

  • the [rows] input has been replaced with [ngModel] via ControlValueAccessor:
const CONTROL_VALUE_ACCESSOR = new Provider(
    NG_VALUE_ACCESSOR, {
        useExisting: forwardRef(() => DataGrid),
        multi: true
});
  • the old columns array is now generated via the 'ng-column' markup as so:
constructor( @Query(DataColumn) cols: QueryList<DataColumn> ) {
        cols.changes.subscribe(() => {
            this.columns = cols.toArray();
        });
    }
  • columns are descriptive and are implemented as seperate components
  • columns can be marked as sortable and widths can be specified per column
import { Component, Input, ContentChild, TemplateRef } from '@angular/core';

@Component({
    selector: 'ng-column',
    template: ''
})

export class DataColumn {
    @Input() public sortable: boolean = false;
    @Input() public filterable: boolean = false; // unused for the moment
    @Input() public width: string;
    @Input() public title: string;
    @Input() public property: string;
    @Input() public sort: string = '';
    @ContentChild(TemplateRef) html: TemplateRef<any>
}
  • columns support templates
import { Component, Input, OnInit, ViewContainerRef } from '@angular/core';
import { DataColumn } from './datacolumn.component';

@Component({
    selector: 'ng-column-loader',
    template: ''
})

export class DataColumnLoader implements OnInit {
    @Input() column: DataColumn;
    @Input() index: number;
    @Input() data: any;

    constructor(private viewContainer: ViewContainerRef) {
    }

    ngOnInit() {
        // load the template in the component view and expose data
        let view = this.viewContainer.createEmbeddedView(this.column.html, {
            '\$implicit': this.column,
            'index': this.index,
            'data': this.data
        });
    }
}

An example using the new markup:

<ng-table [ngModel]="config.rows" (sortChange)="onSortChange($event)">
            <ng-column [title]="'Value'" 
                       [property]="'value'" 
                       [width]="'30%'"
                       [sortable]="true"></ng-column>
            <ng-column [title]="'Actions'">
                <template let-index="index" let-entry="data">
                    <button class="btn btn-secondary" 
                            (click)="onRemove(index, entry)">Remove {{entry.name}}</button>
                </template>
            </ng-column>
</ng-table>
Component({
    templateUrl: 'grid.html',
    directives: [DATAGRID_DIRECTIVES, PAGINATION_DIRECTIVES, CORE_DIRECTIVES, FORM_DIRECTIVES]
})

export class GridPage implements OnInit {
    config: IGridConfig = {
        rows: [],
        page: {
            index: 1,
            count: 15,
            total: 0
        },
        length: 0
    }
    data: Array<any> = [];

    constructor() {
    }

    ngOnInit() {
        this.data.push({
            value: 0,
            name: 'Hello'
        });

        this.data.push({
            value: 1,
            name: 'World'
        });
    }

    public onSortChange(options: any) {
        console.log('sort event', options);
        // TO-DO:
        //      Query using the provided sort options
    }

    public onRemove(index: number, entry: T) {
        console.log('index', index);
        console.log('robot', entry);
    }
}

I consider that components should be more modular in nature in order to offer flexibility.

If you find the above solution to be acceptable and worth integrating into the master branch, let me know and I'll have a fork with a PR in 2 day max.

This implementation has covered most of our use cases so far (I'm also going to try to integrate a row expander soon, that could be a seperate PR, if this one is accepted).

Dynamic columns issue

Hi guys,

I've been trying to dynamically change the columns and the rows on a table. When i create the new array of columns, instead of re-creating the table with the new columns, the table is persisting the old columns, and appending the new once.

We found out that the "issue" is located in ng-table.component.ts starting from line 37.

Can you please give me an info if this is an issue, or if it was intentional made it like this? And if this is not an issue, is there a workaround?

Filter data on button

There is any way to filter data onsubmit from template ( for example setting an input variable of the component)?

Should allow multi-column sorting

In an earlier version of ng2-table, it was possible to sort on multiple columns at once. Now, when you click another column, it removes the sort flag from the previous column. This simpler behavior is probably what most apps want, but it would be nice if there was a config option to enable mutli-column sort for apps that need it.

No value accessor for ''

Hi, I installed it by npm but keep getting this error.

I modified a little bit my project since I am using angular2-seed skafolding. The HTML looks the same as the example:
`import {Component, OnInit} from '@angular/core';
import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgIf} from '@angular/common';
import {PAGINATION_DIRECTIVES} from 'ng2-bootstrap/ng2-bootstrap';
import {NG_TABLE_DIRECTIVES} from 'ng2-table/ng2-table';
import {TableData} from './table-data';

@component({
moduleId: module.id,
selector: 'table-demo',
templateUrl: 'table-section.component.html',
directives: [NG_TABLE_DIRECTIVES, PAGINATION_DIRECTIVES, NgClass, NgIf, CORE_DIRECTIVES, FORM_DIRECTIVES]
})
export class TableDemoComponent implements OnInit {
public rows:Array = [];
public columns:Array = [
{title: 'Name', name: 'name'},
{title: 'Position', name: 'position', sort: false},
{title: 'Office', name: 'office', sort: 'asc'},
{title: 'Extn.', name: 'ext', sort: ''},
{title: 'Start date', name: 'startDate'},
{title: 'Salary ($)', name: 'salary'}
];
public page:number = 1;
public itemsPerPage:number = 10;
public maxSize:number = 5;
public numPages:number = 1;
public length:number = 0;

public config:any = {
paging: true,
sorting: {columns: this.columns},
filtering: {filterString: '', columnName: 'position'}
};

private data:Array = TableData;

public constructor() {
this.length = this.data.length;
}

public ngOnInit():void {
this.onChangeTable(this.config);
}

public changePage(page:any, data:Array = this.data):Array {
console.log(page);
let start = (page.page - 1) * page.itemsPerPage;
let end = page.itemsPerPage > -1 ? (start + page.itemsPerPage) : data.length;
return data.slice(start, end);
}

public changeSort(data:any, config:any):any {
if (!config.sorting) {
return data;
}

let columns = this.config.sorting.columns || [];
let columnName:string = void 0;
let sort:string = void 0;

for (let i = 0; i < columns.length; i++) {
  if (columns[i].sort !== '') {
    columnName = columns[i].name;
    sort = columns[i].sort;
  }
}

if (!columnName) {
  return data;
}

// simple sorting
return data.sort((previous:any, current:any) => {
  if (previous[columnName] > current[columnName]) {
    return sort === 'desc' ? -1 : 1;
  } else if (previous[columnName] < current[columnName]) {
    return sort === 'asc' ? -1 : 1;
  }
  return 0;
});

}

public changeFilter(data:any, config:any):any {
if (!config.filtering) {
return data;
}

let filteredData:Array<any> = data.filter((item:any) =>
  item[config.filtering.columnName].match(this.config.filtering.filterString));

return filteredData;

}

public onChangeTable(config:any, page:any = {page: this.page, itemsPerPage: this.itemsPerPage}):any {
if (config.filtering) {
Object.assign(this.config.filtering, config.filtering);
}
if (config.sorting) {
Object.assign(this.config.sorting, config.sorting);
}

let filteredData = this.changeFilter(this.data, this.config);
let sortedData = this.changeSort(filteredData, this.config);
this.rows = page && config.paging ? this.changePage(page, sortedData) : sortedData;
this.length = sortedData.length;

}
}
`

Empty install from NPM

Running the 'npm i ng2-table --save' command as suggested in the readme installs a placeholder directory with no content.

I tried downloading the zip, moving the content from there into my node_modules, and referencing the index file in there, but that results in some errors as well. Some of them may be from using .37 instead of the current .39 release, but I'm not sure about the pagination errors. I'll try removing those references to get it working.

node_modules/ng2-table/components/pagination/pagination.ts(17,3): error TS7018: Object literal's property 'maxSize' implicitly has an 'any' type.
node_modules/ng2-table/components/pagination/pagination.ts(146,5): error TS2346: Supplied parameters do not match any signature of call target.
node_modules/ng2-table/components/pagination/pagination.ts(151,26): error TS2339: Property 'elementRef' does not exist on type 'Pagination'.
node_modules/ng2-table/components/pagination/pagination.ts(163,22): error TS2339: Property 'cd' does not exist on type 'Pagination'.
node_modules/ng2-table/components/pagination/pagination.ts(179,22): error TS2339: Property 'blur' does not exist on type 'EventTarget'.
node_modules/ng2-table/components/pagination/pagination.ts(182,12): error TS2339: Property 'cd' does not exist on type 'Pagination'.
node_modules/ng2-table/components/pagination/pagination.ts(187,12): error TS7017: Index signature of object type implicitly has an 'any' type.
node_modules/ng2-table/components/pagination/pagination.ts(187,34): error TS7017: Index signature of object type implicitly has an 'any' type.
node_modules/ng2-table/components/pagination/pagination.ts(199,20): error TS7006: Parameter 'number' implicitly has an 'any' type.
node_modules/ng2-table/components/pagination/pagination.ts(199,28): error TS7006: Parameter 'text' implicitly has an 'any' type.
node_modules/ng2-table/components/pagination/pagination.ts(199,34): error TS7006: Parameter 'isActive' implicitly has an 'any' type.
node_modules/ng2-table/components/pagination/pagination.ts(207,20): error TS7006: Parameter 'currentPage' implicitly has an 'any' type.
node_modules/ng2-table/components/pagination/pagination.ts(207,33): error TS7006: Parameter 'totalPages' implicitly has an 'any' type.
node_modules/ng2-table/components/pagination/pagination.ts(208,9): error TS7005: Variable 'pages' implicitly has an 'any[]' type.
node_modules/ng2-table/components/table/filtering.ts(4,14): error TS2305: Module '"angular2/angular2"' has no exported member 'LifecycleEvent'.
node_modules/ng2-table/components/table/filtering.ts(9,27): error TS2307: Cannot find module 'angular2/src/forms/directives/shared'.
node_modules/ng2-table/components/table/filtering.ts(31,18): error TS7006: Parameter 'event' implicitly has an 'any' type.
node_modules/ng2-table/components/table/paging.ts(4,14): error TS2305: Module '"angular2/angular2"' has no exported member 'LifecycleEvent'.
node_modules/ng2-table/components/table/paging.ts(21,16): error TS7006: Parameter 'event' implicitly has an 'any' type.
node_modules/ng2-table/components/table/sorting.ts(4,26): error TS2305: Module '"angular2/angular2"' has no exported member 'LifecycleEvent'.
node_modules/ng2-table/components/table/sorting.ts(24,16): error TS7006: Parameter 'event' implicitly has an 'any' type.
node_modules/ng2-table/components/table/table.ts(69,9): error TS7005: Variable 'sortColumns' implicitly has an 'any[]' type.
node_modules/ng2-table/components/table/table.ts(80,17): error TS7006: Parameter 'column' implicitly has an 'any' type.
node_modules/ng2-table/tsd.d.ts(1,1): error TS6053: File 'node_modules/ng2-table/typings/es6-object.d.ts' not found.
node_modules/ng2-table/tsd.d.ts(2,1): error TS6053: File 'node_modules/ng2-table/node_modules/angular2/bundles/typings/angular2/angular2.d.ts' not found.

How to place pager top and bottom of the table

I want to place the pager in top and bottom of the table. When I put the directive on top and bottom the pager works but the two components are isolated as the page value in the top component is not reflecting in the bottom component. Any quick fix for this?

Problems setting up with >= angular2 beta 3

When trying to use ng2-table, I set it up like this:

npm install --save ng2-table

In index.html:

    <script src="node_modules/ng2-table/ng2-table.js"></script>

Then in config.js:

System.config({
  packages: {
    defaultJSExtensions: true,
    app: {
      format: 'register',
      defaultExtension: 'js'
    }
  },
  paths: {
    lodash: './node_modules/lodash/lodash.js',
    moment: './node_modules/moment/moment.js',
    'ng2-dragula': './node_modules/ng2-dragula',
    'ng2-table': './node_modules/ng2-table',
    require: './node_modules/require/'
  }
});

Now, everything seems fine, typescript finds the correct definition in the node_modules/ng2-table folder, etc. However, when I try to configure the table in the example, on a basic table:

@Component({
  selector: 'work-board-list-view',
  directives: [
    WorkBoardCategoryComponent,
    NG_TABLE_DIRECTIVES
  ],
  providers: [
    WorkItemStatusesService
  ],
  template: `
    <div class="ui segment">
      <ngTable [rows]="rows" [columns]="columns">
      </ngTable>
    </div>
})
export class WorkBoardListViewComponent {
  public rows: Array<any> = [];
  public columns: Array<any> = [
    { title: 'Issue Link', name: 'issueLink'},
    { title: 'Description', name: 'description'},
    { title: 'Project', name: 'project'},
    { title: 'Test Cases', name: 'testCases'},
    { title: 'Status', name: 'status'},
    { title: 'Assigned', name: 'users'}
  ];
}

I get the below error in the screenshot:

Can't find variable: require

2016-02-11_2319

Any help would be greatly appreciated.

Can't bind to 'x' since it isn't a known native property

I'm having problems trying to get the demo to work.

  1. I've installed the module via:
    npm i ng2-table --save
  2. I've added the entries in systemjs.config.js for the map and package fields
var map = {
    ...
    'ng2-table':                    'node_modules/ng2-table'
  };

  var packages = {
   ...
    'ng2-table':                    { defaultExtension: 'js' }
  };
  1. Copied the html and ts from here: http://valor-software.com/ng2-table/

When loading the created component I get the following error:

Can't bind to 'totalItems' since it isn't a known native property

What am I missing?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.