How to use paginator from material angular?

后端 未结 9 1834
清歌不尽
清歌不尽 2020-12-04 11:14

I\'m new to angular and trying to implement pagination in my app. I am trying to use this material component.

With the code below, I can get length,

相关标签:
9条回答
  • 2020-12-04 11:17

    This issue is resolved after spending few hours and i got it working. which is believe is the simplest way to solve the pagination with angular material. - Do first start by working on (component.html) file

     <mat-paginator [pageSizeOptions]="[2, 5, 10, 15, 20]" showFirstLastButtons>
     </mat-paginator>
    

    and do in the (component.ts) file

     import { MatPaginator } from '@angular/material/paginator';
     import { Component, OnInit, ViewChild } from '@angular/core';
    
     export interface UserData {
     full_name: string;
     email: string;
     mob_number: string;
     }
    
     export class UserManagementComponent implements OnInit{
      dataSource : MatTableDataSource<UserData>;
    
      @ViewChild(MatPaginator) paginator: MatPaginator;
    
      constructor(){
        this.userList();
       }
    
        ngOnInit() { }
    
       public userList() {
    
       this._userManagementService.userListing().subscribe(
          response => {
    
          console.log(response['results']);
          this.dataSource = new MatTableDataSource<UserData>(response['results']);
          this.dataSource.paginator = this.paginator;
          console.log(this.dataSource);
    
         },
    
    
          error => {});
    
         }
    
     }
    

    Remember Must import the pagination module in your currently working module(module.ts) file.

      import {MatPaginatorModule} from '@angular/material/paginator';
    
       @NgModule({
          imports: [MatPaginatorModule]
        })
    

    Hope it will Work for you.

    0 讨论(0)
  • 2020-12-04 11:18

    The issue in the original question is that you are not capturing "page" event, to resolve this you need to add (page)='yourEventHandler($event)' as an attribute in the md-paginator tag.

    check a working example here

    You can also check the API docs here

    0 讨论(0)
  • 2020-12-04 11:25

    Hey so I stumbled upon this and got it working, here is how:

    inside my component.html

    <mat-paginator #paginator [pageSize]="pageSize" [pageSizeOptions]="[5, 10, 20]" [showFirstLastButtons]="true" [length]="totalSize"
        [pageIndex]="currentPage" (page)="pageEvent = handlePage($event)">
    </mat-paginator>
    

    Inside my component.ts

    public array: any;
    public displayedColumns = ['', '', '', '', ''];
    public dataSource: any;    
    
    public pageSize = 10;
    public currentPage = 0;
    public totalSize = 0;
    
    @ViewChild(MatPaginator) paginator: MatPaginator;
    
    constructor(private app: AppService) { }
    
    ngOnInit() {
      this.getArray();
    }
    
    public handlePage(e: any) {
      this.currentPage = e.pageIndex;
      this.pageSize = e.pageSize;
      this.iterator();
    }
    
    private getArray() {
      this.app.getDeliveries()
        .subscribe((response) => {
          this.dataSource = new MatTableDataSource<Element>(response);
          this.dataSource.paginator = this.paginator;
          this.array = response;
          this.totalSize = this.array.length;
          this.iterator();
        });
    }
    
    private iterator() {
      const end = (this.currentPage + 1) * this.pageSize;
      const start = this.currentPage * this.pageSize;
      const part = this.array.slice(start, end);
      this.dataSource = part;
    }
    

    All the paging work is done from within the iterator method. This method works out the skip and take and assigns that to the dataSource for the Material table.

    0 讨论(0)
  • 2020-12-04 11:26

    based on Wesley Coetzee's answer i wrote this. Hope it can help anyone googling this issue. I had bugs with swapping the paginator size in the middle of the list that's why i submit my answer:

    Paginator html and list

    <mat-paginator [length]="localNewspapers.length" pageSize=20
                   (page)="getPaginatorData($event)" [pageSizeOptions]="[10, 20, 30]"
                   showFirstLastButtons="false">
    </mat-paginator>
    <mat-list>
       <app-newspaper-pagi-item *ngFor="let paper of (localNewspapers | 
                             slice: lowValue : highValue)"
                             [newspaper]="paper"> 
      </app-newspaper-pagi-item>
    

    Component logic

    import {Component, Input, OnInit} from "@angular/core";
    import {PageEvent} from "@angular/material";
    
    @Component({
      selector: 'app-uniques-newspaper-list',
      templateUrl: './newspaper-uniques-list.component.html',
    })
    export class NewspaperUniquesListComponent implements OnInit {
      lowValue: number = 0;
      highValue: number = 20;
    
      {...} // not relevant logic
    
      // used to build an array of papers relevant at any given time
      public getPaginatorData(event: PageEvent): PageEvent {
        this.lowValue = event.pageIndex * event.pageSize;
        this.highValue = this.lowValue + event.pageSize;
        return event;
      }
    
    }
    
    0 讨论(0)
  • 2020-12-04 11:26

    The tricky part here is to handle is the page event. We can follow angular material documentation up to defining page event function.

    Visit https://material.angular.io/components/paginator/examples for the reference.

    I will add my work with hours of hard work in this regard. in the relevant HTML file should look like as follows,

    <pre>
    <mat-paginator
        [pageSizeOptions]="pageSizeOptions"
        [pageSize]="Size"
        (page)="pageEvent = pageNavigations($event)"
        [length]="recordCount">
    </mat-paginator>
    </pre>
    

    Then go to the relevant typescript file and following code,

    declarations,

    @Input('data') customers: Observable<Customer[]>;
    pageEvent: PageEvent;
    Page: number=0;
    Size: number=2;
    recordCount: number;
    pageSizeOptions: number[] = [2,3,4,5];
    

    The key part of page navigation as follows,

    pageNavigations(event? : PageEvent){
        console.log(event);
        this.Page = event.pageIndex;
        this.Size = event.pageSize;
        this.reloadData();
      }
    

    We require the following function to call data from the backend.

    reloadData() {
    
        this.customers = this.customerService.setPageSize(this.Page ,this.Size);
        this.customerService.getSize().subscribe(res => {
          this.recordCount = Number(res);
         
          console.log(this.recordCount);
        });
      }
    

    Before the aforementioned implementation, our services file should contain the following service call

    setPageSize(page: number, size: number): Observable<any> {
        return this.http.get(`${this.baseUrl}?pageSize=${size}&pageNo=${page}`);
      }
    

    Then all set to go and enable pagination in our app. Feel free to ask related questions thank you.

    0 讨论(0)
  • 2020-12-04 11:29

    Another way to link Angular Paginator with the data table using Slice Pipe.Here data is fetched only once from server.

    View:

     <div class="col-md-3" *ngFor="let productObj of productListData | 
         slice: lowValue : highValue">
           //actual data dispaly  
     </div>
    
    <mat-paginator [length]="productListData.length" [pageSize]="pageSize" 
       (page)="pageEvent = getPaginatorData($event)">
    </mat-paginator> 
    

    Component

        pageIndex:number = 0;
        pageSize:number = 50;
        lowValue:number = 0;
        highValue:number = 50;       
    
      getPaginatorData(event){
         console.log(event);
         if(event.pageIndex === this.pageIndex + 1){
            this.lowValue = this.lowValue + this.pageSize;
            this.highValue =  this.highValue + this.pageSize;
           }
        else if(event.pageIndex === this.pageIndex - 1){
           this.lowValue = this.lowValue - this.pageSize;
           this.highValue =  this.highValue - this.pageSize;
          }   
           this.pageIndex = event.pageIndex;
     }
    
    0 讨论(0)
提交回复
热议问题