Trouble with MatPaginator trying to create a generic component

I’m using angular-material to create a generic table. When I navigate to the details of an object in the table and when I want to open the table page from the menu, it does not render the data until I get some action with the paginator. I think that it is for the paginator, but, I don’t have a solution.

Here is the class in typescript

import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { PageEvent } from '@angular/material/paginator';

@Component({
  selector: 'pc-tabla-paginada',
  templateUrl: './tabla-paginada.component.html',
  styles: `
    #tableDiv { overflow-x: scroll; }
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TablaPaginadaComponent {

  @Input()
  public listaObjetos: any[] = [];

  @Input()
  public columnasAMostrar: string[] = [];

  @Input()
  public nombreColumnas : any = {};

  @Input()
  public encabezadoTabla: string = '';

  @Input()
  public pageSizeOptions: number[] = [5, 10, 20];

  @Input()
  public pageSize: number = 5;

  @Input()
  public length: number = 0;

  @Output()
  public page: EventEmitter<PageEvent> = new EventEmitter();

  @Output()
  public objeto: EventEmitter<any> = new EventEmitter();

  public emitPaginationData(event: PageEvent) {

    this.page.emit(event);
  }

  public enviarObjeto(elemento: any) {
    this.objeto.emit(elemento);
  }

  public esFecha( value: any ): boolean {
    if ( value === '' || value === null || value === undefined) return false;

    const datoProbar = new Date(value);

    if ( typeof value === 'object' && datoProbar.toString() !== 'Invalid Date') {
      return true;
    }
    return false;
  }

}

Here is the HTML

<div class="row col-12">
  <div class="row col-12">
    <h2>{{ encabezadoTabla }}</h2>
    <hr>
  </div>

  <div class="mat-elevation-z8">
    <div class="mat-elevation-z8 row" id="tableDiv">
      <table mat-table [dataSource]="listaObjetos">

        @for (columna of columnasAMostrar; track $index) {
          <ng-container [matColumnDef] = columna >
            <th mat-header-cell *matHeaderCellDef> {{ nombreColumnas[columna] }} </th>
            <td mat-cell *matCellDef="let elemento">
              @if ( columna === 'enableEdition') {
                <button mat-raised-button
                  (click)="enviarObjeto(elemento)">
                  <mat-icon>more_horiz</mat-icon>
                  Más
                </button>
              } @else {
                @if ( esFecha(elemento[columna]) ) {
                  {{elemento[columna] | date:'medium': '':'es-ES' }}
                } @else {
                  {{elemento[columna]}}
                }
              }
            </td>
          </ng-container>
        }

        <tr mat-header-row *matHeaderRowDef="columnasAMostrar"></tr>
        <tr mat-row *matRowDef="let row; columns: columnasAMostrar;"></tr>

      </table>
    </div>
    <div class="row">
      <mat-paginator
        [pageSizeOptions] = "pageSizeOptions"
        [length] = "length"
        [pageSize] = "pageSize"
        showFirstLastButtons
        aria-label="Lista de Pedidos"
        (page)="emitPaginationData($event)">
      </mat-paginator>
    </div>
  </div>
</div>

As it is a generic component, I will call it like this

<pc-tabla-paginada
          [listaObjetos]="listaObjetos"
          [columnasAMostrar]="columnasAMostrar"
          [nombreColumnas]="nombreColumnas"
          [pageSizeOptions]="pageSizeOptions"
          [pageSize]="pageSize"
          [length]="length"
          [encabezadoTabla]="encabezadoTabla"
          (page)="getPaginationData($event)"
          ></pc-tabla-paginada>

So, in the constructor of the object, I’m not subscribing to any petition because it’s generic. I have looked for a lot of solutions, but none of them fit my problem.

4

The issue you’re experiencing, where the data doesn’t render until you interact with the paginator, is likely related to change detection in Angular. Let’s go through some potential solutions:

  1. Force Change Detection:
    Since you’re using OnPush change detection strategy, you might need to force change detection when the data is updated. You can do this by injecting ChangeDetectorRef into your component and calling detectChanges() when the data is updated.
import { ChangeDetectorRef } from '@angular/core';

export class TablaPaginadaComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  @Input() set listaObjetos(value: any[]) {
    this._listaObjetos = value;
    this.cdr.detectChanges();
  }
  get listaObjetos(): any[] {
    return this._listaObjetos;
  }
  private _listaObjetos: any[] = [];
}
  1. Use ngOnChanges:
    Implement the OnChanges interface to detect when the input properties change:
import { OnChanges, SimpleChanges } from '@angular/core';

export class TablaPaginadaComponent implements OnChanges {
  ngOnChanges(changes: SimpleChanges) {
    if (changes['listaObjetos']) {
      // Perform any necessary updates
      this.cdr.detectChanges();
    }
  }
}
  1. Use async pipe:
    If your data is coming from an Observable, consider using the async pipe in your template:
<table mat-table [dataSource]="listaObjetos | async">
  <!-- ... -->
</table>
  1. Trigger change detection in the parent component:
    Ensure that change detection is triggered in the parent component when the data is updated:
import { ChangeDetectorRef } from '@angular/core';

export class ParentComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  updateData() {
    // Update your data
    this.listaObjetos = [...]; // Create a new reference
    this.cdr.detectChanges();
  }
}
  1. Use trackBy function:
    Implement a trackBy function to help Angular identify which items have changed:
export class TablaPaginadaComponent {
  trackByFn(index: number, item: any): any {
    return item.id; // Use a unique identifier from your data
  }
}

And in your template:

<table mat-table [dataSource]="listaObjetos" [trackBy]="trackByFn">
  <!-- ... -->
</table>
  1. Ensure data is loaded before rendering:
    In the parent component, you might want to ensure that the data is fully loaded before passing it to the child component:
export class ParentComponent implements OnInit {
  listaObjetos: any[] = [];

  ngOnInit() {
    this.loadData();
  }

  loadData() {
    // Your data loading logic here
    this.someService.getData().subscribe(data => {
      this.listaObjetos = data;
      this.cdr.detectChanges();
    });
  }
}
  1. Defer rendering:
    You can use *ngIf to defer rendering until the data is available:
<pc-tabla-paginada
  *ngIf="listaObjetos.length > 0"
  [listaObjetos]="listaObjetos"
  ...
></pc-tabla-paginada>

Try implementing these solutions one at a time, starting with forcing change detection (#1) as it’s likely to be the most straightforward fix.

1

As mentioned in the comment, I also have tried several ways to solve the issue. Here is my implementation for reference:

@Component({
  selector: 'app-paginator',
  standalone: true,
  imports: [
    MatButtonModule,
    MatPaginatorModule,
    StylePaginatorDirective,
    MatIconModule,
  ],
  template: `
    <mat-paginator
      #paginator
      appStylePaginator
      [showTotalPages]="2"
      (page)="handlePageEvent($event)"
      [length]="length"
      [pageSize]="pageSize"
      [disabled]="disabled"
      [showFirstLastButtons]="showFirstLastButtons"
      [pageSizeOptions]="showPageSizeOptions ? pageSizeOptions : []"
      [hidePageSize]="hidePageSize"
      [pageIndex]="pageIndex"
      aria-label="Select page"
    >
    </mat-paginator>
  `,
  styles: [
    `
      .mat-mdc-paginator-range-label {
        display: none;
      }

      .mat-mdc-mini-fab {
        --mdc-fab-small-container-shape: 5px;
        margin-right: 1rem;
      }

      .mat-mdc-icon-button[disabled] .mat-mdc-paginator-icon {
        fill: rgba(0, 0, 0, 0.2) !important;
      }
    `,
  ],
  encapsulation: ViewEncapsulation.None,
})
export class PaginatorComponent implements OnChanges {
  @Input() length!: number | null;
  @Input() pageSize!: number;
  @Input() pageSizeOptions: number[] = [5, 10, 25, 100];

  pageIndex = 0;
  hidePageSize = true;
  showPageSizeOptions = false;
  showFirstLastButtons = false;
  disabled = false;
  pageEvent!: PageEvent;

  @ViewChild('paginator', { static: true }) paginator!: MatPaginator;

  constructor(private cdr: ChangeDetectorRef) {}

  handlePageEvent(e: PageEvent) {
    this.pageEvent = e;
    this.length = e.length;
    this.pageSize = e.pageSize;
    this.pageIndex = e.pageIndex;
  }

  private triggerInitialPageEvent() {
    // Create an initial PageEvent
    if (this.length === 0 || !this.length) return;
    const initialPageEvent: PageEvent = {
      pageIndex: this.pageIndex,
      pageSize: this.pageSize,
      length: this.length,
    };

    // Trigger the handlePageEvent method
    this.paginator.page.emit(initialPageEvent);
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['length'] || changes['pageSize']) {
      setTimeout(() => {
        this.triggerInitialPageEvent();
        this.cdr.detectChanges();
      });
    }
  }
}

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật