Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

pagination - Angular MatPaginator doesn`t get initialized

I have 2 components. Both have mat-table and paginators and pagination is working for one component and not working for the other component though the code is similar. Below is my html:

<div class="mat-elevation-z8">
    <mat-table [dataSource]="dataSource" matSort>
        <ng-container matColumnDef="col1">
            <mat-header-cell *matHeaderCellDef mat-sort-header> Column1 </mat-header-cell>
            <mat-cell *matCellDef="let row"> {{row.col1}} </mat-cell>
        </ng-container>

        <ng-container matColumnDef="col2">
            <mat-header-cell *matHeaderCellDef mat-sort-header> Column2 </mat-header-cell>
            <mat-cell *matCellDef="let row"> {{row.col2}} </mat-cell>
        </ng-container>

        <!-- Different columns goes here -->

        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>

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

And below is my code in component.ts:

dataSource: MatTableDataSource<any>;
displayedColumns = ['col1', 'col2', ... ];

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

ngOnInit(): void {
    // Load data
    this.dataSource = new MatTableDataSource(somearray);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
}

Similar code is working for the other component and table is getting rendered with the pagination properly, no clue what's wrong with this code.

Any help would be really appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In my case, the <mat-paginator> element was inside a container that had an *ngIf on it, which did not render until the data loaded asynchronously. This causes this.paginator to be undefined even in ngAfterViewInit. This causes it to silently fail as MatTableDataSource has no problem with you setting paginator to undefined.

The solution was to move the <mat-paginator> outside of the *ngIf'd container

Hopefully, this helps someone who is in the same situation as me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...