Home > Mobile >  Mat-table doesn't "obey" paginator
Mat-table doesn't "obey" paginator

Time:07-30

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 >
<div class = "second-container mat-elevation-z8">
    <mat-table [dataSource]="people" >

        <!-- 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();
      });
  }
}

CodePudding user response:

I think you need to provide dataSource property to the data source of the mat-table (instead of people)

Here:

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

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();
}
  • Related