使用AngularFire2 Firestore数据源的Angular Material 2数据表分页

时间:2018-02-22 11:36:51

标签: angular firebase datatable google-cloud-firestore angular-material2

我在我的控制器中使用来自firestore中'expenses'集合的数据填充了一个可观察数组/ MatTableDataSource,我希望能够在此使用angular material 2分页方法,但找不到任何文档/在线教程,可以说明如何做到这一点。

我的控制器目前设置如下,但分页尝试无效:

import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';

import { MatPaginator, MatTableDataSource, MatSort } from '@angular/material';

import { Observable } from 'rxjs/Observable';

import { AngularFireDatabase } from 'angularfire2/database';

import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';

import { Expense } from '../expenseModel';

@Component({
  selector: 'app-expense-list',
  templateUrl: './expense-list.component.html',
  styleUrls: ['./expense-list.component.scss']
})

export class ExpenseListComponent implements OnInit, AfterViewInit {

  //    tableColumns = [ 'id', 'reference', 'date', 'description', 'category', 'type', 'nominal', 'value', 'taxCode', 'tax', 'total' ];
  tableColumns = [ 'id' ];

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

  expenses = new MatTableDataSource(this.expenses);

  constructor(private db: AngularFirestore) {
    this.expenses = this.db.collection('/expenses', ref => ref.orderBy('id')).valueChanges();
  }

  ngOnInit() {

  }

  ngAfterViewInit() {
    this.expenses.paginator = this.paginator;
  }

  viewExpense(row) {
    console.log('viewExpense(' + row.id + '): ', row);
  }

}

2 个答案:

答案 0 :(得分:0)

因为我很好奇,我很快会把一个示例stackblitz放在一起,完成后在这里发布。以下是我的“方法”......

在我的html中,添加分页,如:

<mat-paginator [length]="length"
    [pageSize]="pageSize"
    [pageSizeOptions]="pageSizeOptions"
    (page)="getExpenses($event)">
</mat-paginator>

在我的组件中,添加分页事件以获取一页数据,例如:

length;
pageSize = 10;  // set default to 10
pageSizeOptions = [5, 10, 25, 100];

constructor(private db: AngularFirestore) { }

ngOnInit() {
    this.getExpenses();
}

getExpenses(event?: PageEvent) {
    this.expenses = this.db.collection('/expenses')
        .orderBy('id')
        .startAt(event.pageIndex)
        .limit(event.pageSize)
        .get();
    this.length = this.expenses.size;
}

更新:我一直在通过Angular Firestore实施分页解决方案的研究引导我Simple Pagination With AngularFire2

答案 1 :(得分:0)

我遇到了类似的问题,并解决了所有问题,将其放入ngOnInit方法

component.ts

  dataSource = new MatTableDataSource<any>();
  displayedColumns = ['id', 'name', 'status']
  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngOnInit() {
    this.db.collection('users').valueChanges()
      .subscribe(users => {
        this.dataSource = new MatTableDataSource<any>(users);
        this.dataSource.paginator = this.paginator;
      })
  }

template.html

<div class="mat-elevation-z8">
  <table mat-table [dataSource]="dataSource" class="w-100">

    ...
  </table>

  <mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
</div>