Mat Paginator is not working properly when used inside a Modal pop up

1.4k Views Asked by At

I'm loading my datasource dynamically from API response inside a modal popup but it seems like Paginator is always undefined as my viewChild MatPaginator is on a modal pop up that open upon a button click.

tried this solution (this link) but no luck

can somebody help me with this. below is screenshot of my code

initialization

enter image description here

setting datasource from api response

enter image description here

final console result where i'm unable to get the pagination reference

enter image description here

thanks in advance!

2

There are 2 best solutions below

1
On

I resolved the same issue with :

setTimeout(() => this.previewResultValues.paginator = this.paginator);

I hope this can help someone one day.

1
On

import {Directive,OnInit,Optional,Output,EventEmitter} from '@angular/core'
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import {MatPaginator} from '@angular/material/paginator';

@Directive({
  selector: '[appPaginator]',
  exportAs: '[appPaginator]'
})
export class PaginatorDirective implements OnInit {
  @Output() paginatorLoaded:EventEmitter <MatPaginator> = new EventEmitter<MatPaginator>()
  ngOnInit()
  {
    setTimeout(()=>{
      if (this.table && this.sort)
        (this.table.dataSource as any).sort=this.sort
      if (this.paginator)
        this.paginatorLoaded.emit(this.paginator)
    })
  }
  constructor(@Optional() private sort:MatSort,@Optional() private table:MatTable<any>,@Optional() private paginator:MatPaginator){}
}

 <table mat-table [dataSource]="DataSource" appPaginator #Sort="matSort" matSort>

        <ng-container matColumnDef="SrNo">
          <th mat-header-cell *matHeaderCellDef mat-sort-header class="commonHeaderCSS"> SrNo
          <td mat-cell *matCellDef="let row; let i = index;">
            {{ i+1 }}
          </td>
        </ng-container>
         <tr mat-header-row *matHeaderRowDef="displayedColumnsForApiFilterCount"></tr>
        <tr mat-row class="example-element-row"
          *matRowDef="let row; columns: displayedColumnsForApiFilterCount; let i = index;"></tr>
      </table>
      
       <mat-paginator appPaginator (paginatorLoaded)="DataSource.paginator=$event" class="mt-3" [pageSize]="10"
      [pageSizeOptions]="[15,30,50,100]">
    </mat-paginator>