Angular 6 : How to implement Pagination and Sorting on Angular Material Table

标签 angular angular-material

如何在 Angular Material DataTable 中传递我的 API 服务数据。我想呈现我的数据而不是这个静态数组。如果我像 *ngFor="let item of service.list" 这样呈现我的数据,那么数据已加载但分页和排序不起作用。请给出一些解决方案或示例。

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'}
];

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource(ELEMENT_DATA);

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }
}

最佳答案

试试这个,使用表的动态列名:

HTML代码:

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8" matSort>
    <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> {{column}} </th>
        <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator [length]="dataSource.length" [pageSize]="10" [pageIndex]="0" [pageSizeOptions]="[3,5,10]" showFirstLastButtons></mat-paginator>

TS代码:

import { DataService } from './data.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';

/**
 * @title Basic use of `<table mat-table>`
 */
@Component({
  selector: 'table-basic-example',
  styleUrls: ['table-basic-example.css'],
  templateUrl: 'table-basic-example.html',
  providers: [DataService]
})

export class TableBasicExample implements OnInit {
  displayedColumns = []
  dataSource = new MatTableDataSource([]);

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(private service: DataService) {
  }

  ngOnInit() {
    this.service.getList().then(res => {
      this.displayedColumns = Object.keys(res[0])
      this.dataSource = new MatTableDataSource(res);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
    })
  }
}

data.service.ts:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class DataService {

  constructor(private http: HttpClient
  ) { }

  private url = "https://jsonplaceholder.typicode.com/todos";

  getList(): Promise<any> {
    const url = `${this.url}`;
    return this.http.get(url)
      .toPromise()
      .catch(this.handleError);
  }
  // handler for error in URL
  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }
}

StackBlitz

关于 Angular 6 : How to implement Pagination and Sorting on Angular Material Table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54176874/

相关文章:

material-design - 如何在 Angular-Material Design 中使用带有 md-autocomplete 的 md-icon?

angular - 将对象返回给服务的调用者

Angular4 更改 md-button 的波纹颜色

angularjs - Angular JS 的 Material Design Lite 渲染问题

angular - 带有两行标题的 Mat-table,使用 Angular 8

angular - 无法升级到 Angular 6,范围无效

Angular 4路由到外部网址

angular - 单页应用 : authorization code grant with OAuth2

http - angular2 http.delete on-memory-web-api

angular - 带嵌套对象的 BreezeJs 查询