Home > Software design >  how can use mat-paginator for paging a custom card-based component into parent component view?
how can use mat-paginator for paging a custom card-based component into parent component view?

Time:01-02

I built a component which is card-based table. it has an input named: @Input() tableModelRows!: Object[]; that receives an array of objects. elements of this array are considered as rows of the table and each one of them is imported to a card-based component: <app-card-based-table-rows> using *ngFor to show them in rows. so, due to the large number of rows (elements of the array), I want to utilize mat-paginator to show them in several pages. how can use the mat-paginator for this purpose? Actually, how to paging <app-card-based-table-rows> components (child components)? content of .ts and .HTML file of card-based-table component (parent component) are following:

import {Component, Input, OnInit} from '@angular/core';


@Component({
  selector: 'app-card-based-table',
  templateUrl: './card-based-table.component.html',
  styleUrls: ['./card-based-table.component.css']
})
export class CardBasedTableComponent implements OnInit {

  @Input() tableHeaderTitles!: string[];
  @Input() tableModelRows!: Object[];
  //...

  constructor() {}

  ngOnInit(): void {

  }
}
<!-- insert table header selector-->
<app-card-based-table-header [headerTitles]="tableHeaderTitles">
</app-card-based-table-header>

<!-- insert table body selector-->
<app-card-based-table-rows *ngFor="let row of tableModelRows" [rowTitles]="row">
</app-card-based-table-rows>

CodePudding user response:

A mat-paginator can be used "standalone". You only need "feed" with pageIndex (0 based index),pageSize, length and pageSize options.

<mat-paginator #paginator [length]="length"
              [pageIndex]="pageIndex"
              [pageSize]="pageSize"
              [pageSizeOptions]="[5, 10, 25, 100]"
              (page)="changePage($event)
              >
</mat-paginator>

length=100;
pageIndex=0;
pageSize=10;

See the templalte reference variable #paginator. So you can use directly in your .html using slice pipe

<ng-content *ngFor="let item of myArray|slice:
             (paginator.pageIndex*paginator.pageSize):
             ((paginator.pageIndex 1)*paginator.pageSize)>
...
</ng-content>

If yu need more control, you can also add the event (page) to control your items

<mat-paginator #paginator
               ...
              (page)="changePage($event)
              >
</mat-paginator>

changePage(event:PageEvent){
   console.log("you're in page index",event.pageIndex)
   ..make something more...
}

Or get the paginator using ViewChild

@ViewChild(MatPaginator,{static:true}) paginator:MatPaginator
  • Related