MatPaginator未定义

Kra*_*am_ 5 angular-material2

我已经复制了这个案例: Angular 5 Material Table没有从服务中获取数据

但是当我尝试从paginator访问任何属性时,我会从此对象中获得未定义的错误.

有任何想法吗?

谢谢

小智 27

我遇到了同样的问题.将mat-paginator标签放在*ngIf之外解决了我的问题.确保它在没有任何条件的情况下可用于组件类.

  • @Logan_B 使用 [hidden] 而不是 *ngIf (2认同)

Jos*_*ndo 6

可能导致mat-paginator的某些问题未定义:

  1. 您忘记了导入app.module.ts import { MatPaginatorModule } from '@angular/material';,然后在ngModule 中的imports数组中声明了导入。

    @NgModule({声明:[某物],导入:[MatPaginatorModule]});

  2. 将MatPaginator导入您正在使用的组件内: import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material';

  3. 将MatDataSource设置为none。(仅当您要从服务器获取异步数据时才需要这样做)

    this.dataSource =新的MatTableDataSource([]);

  4. 确保将mat-paginator的length属性设置为返回的数据行的长度。

  5. NgAfterViewInit方法中设置分页器,或者如果不起作用,请尝试:

私人分页器:MatPaginator;私人排序:MatSort;

@ViewChild(MatSort) set matSort(ms: MatSort) {
    this.sort = ms;
    this.setDataSourceAttributes();
}

@ViewChild(MatPaginator) set matPaginator(mp: MatPaginator) {
    this.paginator = mp;
    this.setDataSourceAttributes();
}

setDataSourceAttributes() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;

    if (this.paginator && this.sort) {
        this.applyFilter('');
    }
}
Run Code Online (Sandbox Code Playgroud)


You*_*ani 6

在某些情况下,问题与条件外部 div 有关。前任:

<div *ngIf="condition">
    ...

   <mat-paginator ....>
</div>
Run Code Online (Sandbox Code Playgroud)

对于这种情况,只需将 *ngIf="condition" 替换为 [hidden]="!condition" 即可。更多详情请参考https://github.com/angular/components/issues/10205


Pra*_*Vig 5

我遇到了类似的问题,这就是我如何让它工作的:

我的初始代码设置

组件.html

    <div class="chart-wrapper" *ngIf="viewType === 'chart'; else table;">
        // Load Chart Here
    </div>

    <ng-template #table>
        // Load Table Here

        <mat-paginator
            #paginator
            [length]="tableDataSource.data ? tableDataSource.data.length : 0"
            [pageSize]="pageSize"
            [pageSizeOptions]="pageSizeOptions"
            (page)="onPageChange($event)"
        ></mat-paginator>
    </ng-template>
Run Code Online (Sandbox Code Playgroud)

组件.ts

columns: string[] = [];
tableDataSource: MatTableDataSource<any[]> = new MatTableDataSource([]);
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
pageIndex = 0;
pageSize = 10;
pageSizeOptions = [10, 15, 20];

ngOnInit() {
    this.getTableData();
}

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

getTableData() {
    // After getting data from API
    this.tableDataSource.data = apiResponse;
}
Run Code Online (Sandbox Code Playgroud)

解决方案

声明 Mat Paginator 时放置static: false

@ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
Run Code Online (Sandbox Code Playgroud)

然后在数据加载到tableDataSource后将分页器设置到tableDataSource 上

this.tableDataSource.data = apiResponse;
this.tableDataSource.paginator = this.paginator;
Run Code Online (Sandbox Code Playgroud)

感谢cisco336 在此线程上的解决方案

令我惊讶的是,没有人评价这个解决方案。