我正在创建一个表格,使用表格Angular 材料作为参考,我使用此示例https://material.angular.io/components/table/examples
以下是我目前掌握的情况:
超文本标记语言
<mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
<div class="mat-elevation-z8">
<table mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
<td mat-cell *matCellDef="let row"> {{row.name}} </td>
</ng-container>
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Id </th>
<td mat-cell *matCellDef="let row"> {{row.id}} </td>
</ng-container>
<ng-container matColumnDef="release">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Release</th>
<td mat-cell *matCellDef="let row"> {{row.first_air_date}} </td>
</ng-container>
<ng-container matColumnDef="description">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Description </th>
<td mat-cell *matCellDef="let row" [style.color]="row.color"> {{row.overview}} </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, 25, 100]"></mat-paginator>
</div>
组件. ts
import { Component, ViewChild, OnInit } from '@angular/core';
import { MoviesService } from '../movies.service';
import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';
import { DatatableComponent } from '@swimlane/ngx-datatable';
@Component({
selector: 'app-tv-shows',
templateUrl: './tv-shows.component.html',
styleUrls: ['./tv-shows.component.scss']
})
export class TvShowsComponent implements OnInit {
displayedColumns: string[] = ['name', 'id', 'release', 'description'];
dataSource: any;
@ViewChild(DatatableComponent) table: DatatableComponent;
constructor(private moviesService: MoviesService) {
this.moviesService.getPopularTVShows().subscribe(res => {
this.dataSource = res.results;
});
}
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
}
当我运行我的应用程序时,数据完美地显示在表中,但我得到以下错误:
ERROR TypeError: Cannot set property 'paginator' of undefined
所以排序、过滤和分页都不起作用
我需要帮助:
我在上面的代码中做错了什么?任何帮助都将不胜感激。
3条答案
按热度按时间rdrgkggo1#
错误提示您试图在
this.dataSource
仍然是undefined
时赋值this.dataSource.paginator
。请在初始化之后进行赋值。另外,当你想使用分页器、排序器或者过滤器时,你必须使用
MatTableDataSource
类,使用原始数据作为dataSource
是不够的:pcrecxhr2#
您没有做错任何事情。就像下面的代码
dataSource: MatTableDataSource<Order> = new MatTableDataSource();
一样将新示例分配给ur dataSource,也感谢Kim Kern的解释sigwle7e3#