【问题标题】:Angular 6: How to implement Pagination and Sorting on Angular Material TableAngular 6:如何在 Angular 材料表上实现分页和排序
【发布时间】:2019-01-14 06:52:44
【问题描述】:

如何在 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;
  }
}

【问题讨论】:

  • 你为什么使用*ngFor?必须是mat-table [dataSource]="service.list"
  • 查看此演示以获得帮助,stackblitz.com/edit/…
  • 我的数据已加载,但问题是排序和分页不起作用@john

标签: angular angular-material


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-01-01
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    相关资源
    最近更新 更多