Issue
I have this mat-table that doesn't seem to "obey" the paginator: https://i.stack.imgur.com/HLJrI.png
As you can see, there are 7 people (all of them), showing on the first page, instead of 5. I have tried every tutorial on paginators, including Angular Materials documentation itself, but none of them have solved my problem.
HTML
<div class="first-container">
<div class = "second-container mat-elevation-z8">
<mat-table [dataSource]="people" class="table">
<!-- NIF Column -->
<ng-container matColumnDef="nif">
<mat-header-cell *matHeaderCellDef> NIF </mat-header-cell>
<mat-cell *matCellDef="let person"> {{person.nif}} </mat-cell>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
<mat-cell *matCellDef="let person"> {{person.name}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row (click)="updateDialog(row.nif, row.name)" *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
<mat-paginator #page [pageSizeOptions]="[5, 10, 25, 100]" showFirstLastButtons></mat-paginator>
</div>
TS
export class PeopleComponent implements OnInit {
people: IPerson[] = [];
displayedColumns: string[] = ['nif', 'name'];
dataSource: MatTableDataSource<IPerson>;
@ViewChild('page')
paginator: MatPaginator;
constructor(private service: PeopleService, public dialog: MatDialog) {}
ngOnInit(): void {
this.getPeople();
}
getPeople(): void {
this.service.getPeople().subscribe((person) => {
this.dataSource = new MatTableDataSource((this.people = person));
this.dataSource.paginator = this.paginator;
});
}
openDialog() {
this.dialog
.open(AddPeopleComponent)
.afterClosed()
.subscribe(() => {
this.getPeople();
});
}
updateDialog(nif: string, name: string) {
this.dialog
.open(UpdatePeopleComponent, {
data: {
nif: nif,
name: name,
},
})
.afterClosed()
.subscribe(() => {
this.getPeople();
});
}
}
Solution
I think you need to provide dataSource
property to the data source of the mat-table (instead of people
)
Here:
<mat-table [dataSource]="dataSource" class="table">
Another change you can do is to call gePeople
on ngAfterViewInit
instead of onInit
. This way you can make sure that paginator
is initialized.
Example:
ngAfterViewInit(): void {
this.getPeople();
}
Answered By - Telman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.