Set pageIndex in Angular material paginator not working when page loaded for first time
Asked Answered
S

1

6

I want Angular's Paginator starts from second page when page refreshed but I got this error

ERROR TypeError: Cannot set property 'pageIndex' of undefined

I tried to use delay but it is not a good solution,

HTML

<mat-paginator #paginator
  showFirstLastButtons
  [length]="length"
  [pageSize]="pageSize"
  [pageSizeOptions]="pageSizeOptions"
  (page)="pageEvent = changePage($event)">
</mat-paginator>

TypeScript

  @ViewChild('paginator', { static: true }) paginator;
  pageSize = 5;
  pageSizeOptions: number[] = [5, 10, 50, 100];
  pageEvent: PageEvent;
  buttonDisablity = true;

  ngOnInit(): void {
    this.paginator.pageIndex = 2;
  }

Softboiled answered 15/7, 2020 at 9:8 Comment(0)
P
8

ngOnInit hook doesn't have access of viewchild instance. ViewChild instance is available only in or after afterViewInit hook.

ngAfterViewInit(): void {
    this.paginator.pageIndex = 2;
}
Protozoal answered 15/7, 2020 at 9:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.