需要对“ ng-2表”的数据将如何传递到行的解释。我需要对工作流程的解释

时间:2019-05-08 18:36:13

标签: angular ngtable

  1. 我想了解ng2-table的工作流程。我对数据如何传递到<ng-table [config]="config" (tableChanged)="onChangeTable(config)" (cellClicked)="onCellClick($event)" [rows]="rows" [columns]="columns">感到困惑 “选择器标记。 对于参考,请找到链接:“ https://valor-software.com/ng2-table/” 在“” TableDemoComponent。“”“ ts文件中,”“ TableData”“'的数据如何将对象值传递给ng2表行。
  2. 我了解传递列标题值。但是行数据如何传递给“''NgTableComponent''',请有人帮我。 请在下面找到完整代码:

TableDemoComponent.ts


    import { Component, OnInit } from '@angular/core';
    import { TableData } from './table-data';

    // webpack html imports
    let template = require('./table-demo.html');

    @Component({
      selector: 'table-demo',
      template
    })
    export class TableDemoComponent implements OnInit {
      public rows:Array<any> = [];
      public columns:Array<any> = [
        {title: 'Name', name: 'name', filtering: {filterString: '', placeholder: 'Filter by name'}},
        {
          title: 'Position',
          name: 'position',
          sort: false,
          filtering: {filterString: '', placeholder: 'Filter by position'}
        },
        {title: 'Office', className: ['office-header', 'text-success'], name: 'office', sort: 'asc'},
        {title: 'Extn.', name: 'ext', sort: '', filtering: {filterString: '', placeholder: 'Filter by extn.'}},
        {title: 'Start date', className: 'text-warning', 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: ''},
        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 ? (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 !== '' && columns[i].sort !== false) {
            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 {
        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);
      }
    }


###Parent HTML File###
<div class="row">
  <div class="col-md-4">
    <input *ngIf="config.filtering" placeholder="Filter all columns"
           [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>
<pre *ngIf="config.paging" class="card card-block card-header">Page: {{page}} / {{numPages}}</pre>

TableData.ts


    export const TableData: Array<any> = [
      {
        'name': 'Victoria Cantrell',
        'position': 'Integer Corporation',
        'office': 'Croatia',
        'ext': '0839',
        'startDate': '2015/08/19',
        'salary': 208.178
      }, {
        'name': 'Pearl Crosby',
        'position': 'In PC',
        'office': 'Cambodia',
        'ext': '8262',
        'startDate': '2014/10/08',
        'salary': 114.367
      }
    ];

最终代码

NgTableComponent


    @Component({
      selector: 'ng-table',
      template: `
        <table class="table table-striped table-bordered dataTable"
               role="grid" style="width: 100%;">
          <thead>
          <tr role="row">
            <th *ngFor="let column of columns" [ngTableSorting]="config" [column]="column" (sortChanged)="onChangeTable($event)">
              {{column.title}}
              <i *ngIf="config && column.sort" class="pull-right fa"
                [ngClass]="{'fa-chevron-down': column.sort === 'desc', 'fa-chevron-up': column.sort === 'asc'}"></i>
            </th>
          </tr>
          </thead>
          <tbody>
          <tr *ngFor="let row of rows">
            <td *ngFor="let column of columns">{{getData(row, column.name)}}</td>
          </tr>
          </tbody>
        </table>
    `,
      directives: [NgTableSortingDirective, NgClass, CORE_DIRECTIVES]
    })
    export class NgTableComponent {
      // Table values
      @Input() public rows:Array<any> = [];
      @Input() public config:any = {};

      // Outputs (Events)
      @Output() public tableChanged:EventEmitter<any> = new EventEmitter();

      @Input()
      public set columns(values:Array<any>) {
        values.forEach((value:any) => {
          let column = this._columns.find((col:any) => col.name === value.name);
          if (column) {
            Object.assign(column, value);
          }
          if (!column) {
            this._columns.push(value);
          }
        });
      }

      public get columns():Array<any> {
        return this._columns;
      }

      public get configColumns():any {
        let sortColumns:Array<any> = [];

        this.columns.forEach((column:any) => {
          if (column.sort) {
            sortColumns.push(column);
          }
        });

        return {columns: sortColumns};
      }

      private _columns:Array<any> = [];

      public onChangeTable(column:any):void {
        this._columns.forEach((col:any) => {
          if (col.name !== column.name) {
            col.sort = '';
          }
        });
        this.tableChanged.emit({sorting: this.configColumns});
      }

      public getData(row:any, propertyName:string):string {
        return propertyName.split('.').reduce((prev:any, curr:string) => prev[curr], row);
      }
    }

请告诉我有关### TableData ###的数据如何从### NgTableComponent ###组件类中移到enter code here s。请详细说明。 谢谢

0 个答案:

没有答案