使用mat-paginator和mat-table,使用可观察数组作为数据源

时间:2019-11-13 17:28:37

标签: angular typescript angular-material observable mat-table

我正在使用一个可观察的数组作为数据源。这工作正常,除了我现在不知道如何使用分页器。下面是html和ts

html

 <table mat-table #TABLE [dataSource]="cards" class="mat-elevation-z8">          
                <!-- Email Column -->
             <ng-container matColumnDef="date">
                <th mat-header-cell *matHeaderCellDef  class="tbl-th"> Date </th>
                <td mat-cell *matCellDef="let element"> {{core.pretifyDate(element.date)}} </td>
              </ng-container>

            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr mat-row *matRowDef="let row; columns: displayedColumns;">
            </tr>
          </table>
          <mat-paginator [pageSizeOptions]="[5, 10, 20, 50, 100]" [pageSize]="pageSize" showFirstLastButtons></mat-paginator>

.ts

export class CardQueueComponent implements OnInit {

  @ViewChild('TABLE', {static: false}) table: MatTable<any>;
  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;

  displayedColumns: string[] = [ 'image', 'customer', 'email',  'date', 'process' ];
  cards: Observable<Card[]> 
  pageSize = 5


  constructor(public dataSvc: SBDataService,
              public core:CoreService,
              private changeDetectorRefs: ChangeDetectorRef,
              ) { }

    async ngOnInit() {

      this.cards = this.dataSvc.fetchCards().pipe(
        map((cards: any) => cards.map(cardObj => {
          var c = new Card(cardObj.key, cardObj._frontImageUrl, cardObj._date, cardObj._rawData)

        return c
      }))
    );


    this.changeDetectorRefs.detectChanges();

    //this.dataSource.paginator = this.paginator;

  }

}

因此,在直接关联卡片可观察到后,我需要弄清楚分页器上的最后一条注释行。请指教

1 个答案:

答案 0 :(得分:2)

您只需要引用其中的表的DataSource and set your paginator。例如:

dataSource = new MatTableDataSource()

async ngOnInit() {

  this.dataSvc.fetchCards().pipe(
    map((cards: any) => cards.map(cardObj => {
      var c = new Card(cardObj.key, cardObj._frontImageUrl, cardObj._date, cardObj._rawData)
  })).subscribe(cards => this.dataSource.data = cards);

);

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

  <mat-table [dataSource]="dataSource">