简体   繁体   中英

how to get data from static JSON for table, https://github.com/valor-software/ng2-table.iam using ng-2 table

how to get data from json rather from table-data.ts iam confused.tried my best cant able to find the solution.where should i do alteration i think from private data:array=TableData; It will be helpful if anyone give a solution.

Demo.component.ts

export class TableDemoComponent implements OnInit { public rows:Array<any> = [];
public columns:Array<any> = [
{title: 'Company', name: 'name', filtering: {filterString: '', placeholder: 'Filter by name'}},
{
  title: 'Position',
  name: 'position',
  sort: false,
  filtering: {filterString: '', placeholder: 'Filter by position'}
},
{title: 'Location', name: 'office', sort: '', filtering:     {filterString: '', placeholder: 'Filter by Location'}},
{title: 'Date', className: 'text-warning', name: 'startDate'},];
 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: ''},
className: ['table-striped', 'table-bordered']
};
private data:Array<any> = TableData;
public constructor() {
this.length = this.data.length;
}
public ngOnInit():void {
this.onChangeTable(this.config);
}
public changePage(page:any, data:Array<any> = this.data):Array<any> {
let start = (page.page - 1) * page.itemsPerPage;
let end = page.itemsPerPage > -1 (startpage.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!==''&&columns[i].sort!==false{columnNamecolumns[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 {
  let filteredData:Array<any> = data;
  this.columns.forEach((column:any) => {
  if (column.filtering) {
  filteredData = filteredData.filter((item:any) => {
  return item[column.name].match(column.filtering.filterString); });
  }
  });
 if (!config.filtering) {
  return filteredData;
}
if (config.filtering.columnName) {
  return filteredData.filter((item:any) =>        item[config.filtering.columnName].match(this.config.filtering.filterString));
}
let tempArray:Array<any> = [];
filteredData.forEach((item:any) => {
  let flag = false;
  this.columns.forEach((column:any) => {
    if     (item[column.name].toString().match(this.config.filtering.filterString)) {
      flag = true;
    }
  });
  if (flag) {
    tempArray.push(item);
  }
});
filteredData = tempArray;
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;
}
public onCellClick(data: any): any {
console.log(data);
}}

Datatable.ts

export const TableData:Array<any> = [
{
'name': 'Victoria Cantrell',
'position': 'Integer Corporation',
'office': 'Croatia',
'ext': `<strong>0839</strong>`,
'startDate': '2015/08/19',
'salary': 208.178
}, {
'name': 'Pearl Crosby',
'position': 'In PC',
'office': 'Cambodia',
'ext': `<strong>8262</strong>`,
'startDate': '2014/10/08',
'salary': 114.367
 }, {
'name': 'Colette Foley',
'position': 'Lorem Inc.',
'office': 'Korea, North',
'ext': '8968',
'startDate': '2015/07/19',
'salary': 721.473
}
];

Table-demo.html

       <div class="row">
       <div class="col-md-4">
       <input *ngIf="config.filtering" placeholder="Filter allcolumns"
       [ngTableFiltering]="config.filtering"
       class="form-control"
       (tableChanged)="onChangeTable(config)"/>
       </div>
       </div>
       <br>
       <ng-table [config]="config"
       (tableChanged)="onChangeTable(config)"
       (cellClicked)="onCellClick($event)"
       [rows]="rows" [columns]="columns">
        </ng-table>
        <pagination *ngIf="config.paging"
        class="pagination-sm"
        [(ngModel)]="page"
        [totalItems]="length"
        [itemsPerPage]="itemsPerPage"
        [maxSize]="maxSize"
        [boundaryLinks]="true"
        [rotate]="false"
        (pageChanged)="onChangeTable(config, $event)"
        (numPages)="numPages = $event">
        </pagination>

If you wanted to use the TableData in a different file you would have to import it. I have added an example at the top that show you how to import it. All you do is just create another file and import what you need. I tidied up your code and fixed some syntax errors and put some notes next to bits where stuff was undefined which would throw errors also put some explanations next to the top in how to import things:

import {OnInit} from "@angular/core"
import {TableData} from "./test2" //test2 is the name of the file

// ./ current directory
// ../../ up two directories

export class TableDemoComponent implements OnInit {
    public rows: Array<any> = [];

    public columns: Array<any> =
        [
            {
                title: 'Company',
                name: 'name',
                filtering: {
                    filterString: '', placeholder: 'Filter by name'
                }
            },
            {
                title: 'Position',
                name: 'position',
                sort: false,
                filtering: {
                    filterString: '', placeholder: 'Filter by position'
                }
            },
            {
                title: 'Location',
                name: 'office',
                sort: '',
                filtering: {
                    filterString: '', placeholder: 'Filter by Location'
                }
            },
            {
                title: 'Date',
                className: 'text-warning',
                name: 'startDate'
            }
        ];

    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: ''},
        className: ['table-striped', 'table-bordered']
    };

    private data: Array<any> = TableData;

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

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

    public changePage(page: any, data: Array<any> = this.data): Array<any> {
        let start = (page.page - 1) * page.itemsPerPage;

        //startpage is not defined
        let end = page.itemsPerPage > -1 ? startpage.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 !== '' && columns[i].sort !== false) {
                //columnNamecolumns is not defined
                columnNamecolumns[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 {
        let filteredData: Array<any> = data;
        this.columns.forEach((column: any) => {
            if (column.filtering) {
                filteredData = filteredData.filter((item: any) => {
                    return item[column.name].match(column.filtering.filterString);
                });
            }
        });
        if (!config.filtering) {
            return filteredData;
        }
        if (config.filtering.columnName) {
            return filteredData.filter((item: any) => item[config.filtering.columnName].match(this.config.filtering.filterString));
        }
        let tempArray: Array<any> = [];
        filteredData.forEach((item: any) => {
            let flag = false;
            this.columns.forEach((column: any) => {
                if (item[column.name].toString().match(this.config.filtering.filterString)) {
                    flag = true;
                }
            });
            if (flag) {
                tempArray.push(item);
            }
        });
        filteredData = tempArray;
        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;
    }

    public onCellClick(data: any): any {
        console.log(data);
    }
}

I hope this is what you meant for. I am reading my data from external source (not json - but I think this is the same) by this way:

public constructor(private dataService: DataService ){
      this.dataService.getUsers().then(users => {this.data = users; this.length = this.data.length;}).
         catch(error => this.error = error);
  }

  public ngOnInit():void {
       this.dataService.getUsers().then(users => {this.data = users;  this.onChangeTable(this.config);}).
         catch(error => this.error = error);
  }

in this example my data is users. I am calling it from my data service. I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM