Max
Max

Reputation: 442

Showing more rows of a table with pagination in angular

I Have a table on angular that shows data from an API, I want to be able to show just a limited number of rows for example 5 first rows, and add an option to show more which will show another 5 rows along with pagination if the users want to see other rows.

Here is the code I used for the file-table.component.html

<div class="centered-content">
  <table class="table">
    <thead>
      <tr>
        <th>CARD_NUMBER</th>
        <th>TRANSACTION_AMOUNT</th>
        <th>TERMINAL_ID</th>
        <th>EXTERNAL_STAN</th>
        <th>TRANSACTION_DATE</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let row of Transactions[1].csvData; let i = index">
        <th>{{ row.CARD_NUMBER }}</th>
        <td>{{ row.TRANSACTION_AMOUNT }}</td>
        <td>{{ row.TERMINAL_ID }}</td>
        <td>{{ row.EXTERNAL_STAN }}</td>
        <td>{{ row.TRANSACTION_DATE }}</td>
      </tr>
    </tbody>
  </table>
</div>

For the file-table.component.ts.

import { Component, OnInit } from '@angular/core';
import { CrudService } from '../../services/crud.service';
@Component({
  selector: 'app-file-table',
  templateUrl: './file-table.component.html',
  styleUrls: ['./file-table.component.scss'],
})
export class FileTableComponent implements OnInit {
  Transactions: any = [];
  constructor(private crudService: CrudService) {}

  ngOnInit(): void {
    this.crudService.GetTransactions().subscribe((res) => {
      console.log(res);
      this.Transactions = res;
    });
  }
}

This is the service that was used to get the data :

import { Injectable } from '@angular/core';
import { Tansaction } from './Transactions';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
import {
  HttpClient,
  HttpHeaders,
  HttpErrorResponse,
} from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class CrudService {
  // Node/Express API
  REST_API: string = 'http://localhost:4000/trans-list';
  // Http Header
  httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
  constructor(private httpClient: HttpClient) {}

  // Get all objects
  GetTransactions() {
    return this.httpClient.get(`${this.REST_API}`);
  }
  // Error
  handleError(error: HttpErrorResponse) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      // Handle client error
      errorMessage = error.error.message;
    } else {
      // Handle server error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.log(errorMessage);
    return throwError(errorMessage);
  }
}

Upvotes: 0

Views: 1866

Answers (1)

Eliseo
Eliseo

Reputation: 57939

if you get all the data at time you can use

  <tr *ngFor="let row of Transactions[1].csvData|slice:0,(page+1)*5; let i = index">
    <th>{{ row.CARD_NUMBER }}</th>
     ...
  </tr>
  <button *ngIf="(page+1)*5<Transactions[1].csvData.length"
          (click)="page=page+1" >
         5 more
  </button>

  page:number=0
  

If you want to get the data step by step, your service need return the "next 5 rows" and the total rows

So, I imagine your service has a function like

  GetTransactionsPaginate(page:number) {
    return this.httpClient.get(`${this.REST_API}`,{page:page});
  }    

than return and object like:

   {
     totalRows:300
     data:[{CARD_NAME:"..."},{CARD_NAME:"..."}]
   }

And you has a function

   Transactions:any[]=[] //<--declare at first as empty array
   page:number=0;

   getNewData(){
     this.crudService.GetTransactionsPaginate(this.page).subscribe(res=>{
       this.page++;
       this.Transactions=this.Transactions.concat(res.data)
       this.total=res.totalRows;
     })
   } 

Well, the function of the service can also has as parameter the last transaction or another variable you use

Upvotes: 1

Related Questions