Search code examples
angularangular-materialmat-pagination

ERROR TypeError: this.paginator is undefined


I am using custom pagination in a custom component, which is then being called in a component to display pagination. However I am running into this error.

Custom pagination is working correctly because its usued in another project as well.

Here is my component. Is there anything that I am missing?

  @ViewChild(MatPaginatorComponent, { static: true }) paginator: MatPaginatorComponent;
  data: {
     offset: number;
     limit: number;
  };


  ngAfterViewInit(): void {
    this.data$
      .pipe(
        untilDestroyed(this),
        map((settings) => {
          this.data= settings;
          this.paginator.pageIndex = 1;
          this.paginator.pageSize = 10;
          return this.data;
        }),
      )
      .subscribe();
    if (this.paginator && this.data) {
      this.paginator.pageSize = 10; 
      this.paginator.pageIndex = 1; 
      this.matDataSource.paginator = this.paginator;
    }

    this.cdr.detectChanges();
  }


Solution

  • It looks like you are using this.paginator inside ngAfterViewInit(), which is not initialised on time.

    If you put the In a setTimeout() for delay the error might go away. once you know the issue is an initialisation, and if you don't like setTimeout you can figure out where to load this.paginator

    setTimeout(() =>{
       if (this.paginator && this.data) {
              this.paginator.pageSize = 10; 
              this.paginator.pageIndex = 1; 
              this.matDataSource.paginator = this.paginator;
            } 
    }, 0)