Diako Sharifi
Diako Sharifi

Reputation: 463

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

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;
  }

Upvotes: 6

Views: 9318

Answers (1)

micronyks
micronyks

Reputation: 55443

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;
}

Upvotes: 8

Related Questions