Alfredo Izquierdo
Alfredo Izquierdo

Reputation: 167

How paginate from data is coming from a json in Angular

I am new in this I have a service with HTTPclient is get all the data from a JSON file have 1000 register, how I can make pagination, for example, show the first 10 and paginate it

this is my service

@Injectable({
  providedIn: 'root'
})
export class ProductsService {

  constructor(private http:HttpClient ) { 
  }

  getPorducts(): Observable<Product[]> {

    return this.http.get<Product[]>('assets/data/DATA.json');

  }
}

I just use it on my home component

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styles: []
})
export class HomeComponent implements OnInit {

  public products: any[] = [];


  constructor(private _Products: ProductsService) { }

  public lastKey: any[] = [];

  ngOnInit() {
    this._Products.getPorducts().subscribe(data => {
      if (data) {
        this.products = data;
      }
    });


  }

How I can do it? thanks in advance

Upvotes: 1

Views: 3711

Answers (1)

Abolfazl Roshanzamir
Abolfazl Roshanzamir

Reputation: 14802

Lets start by reading data form the service(In service we read data form the json file)

export class AppComponent implements OnInit {

 public products: any[] = [];

 curPage: number;
 pageSize: number;

 constructor(private _Products: ProductService) { }

 ngOnInit(): void {
   this._Products.getJSON().subscribe(response => {
     this.products = response.items;
   });

   this.curPage = 1;
   this.pageSize = 10; // any page size you want 
 }

 numberOfPages() {
   return Math.ceil(this.products.length / this.pageSize);
 };
}

Here we have added two variable, curPage and pageSize that can be updated according to the requirement. (click) will navigate user to the desired page. You can update the look and feel for pagination control according to your needs.

and finally in your html :

 <table class="table table-sm table-bordered">
     <thead>
         <tr>
             <th>Id</th>
             <th>Name</th>
         </tr>
     </thead>
     <tbody>
         <tr *ngFor="let item of products | slice: (curPage * pageSize) - pageSize :curPage * pageSize">
             <td>{{item.id}}</td>
             <td>{{item.name}}</td>
         </tr>
     </tbody>
 </table>
 <p class="pagination">
     <button [disabled]="curPage == 1" (click)="curPage = curPage - 1">PREV</button>
     <span>Page {{curPage}} of {{ numberOfPages() }}</span>
     <button [disabled]="curPage >= list.length/pageSize" (click)="curPage = curPage + 1">NEXT</button>
 </p>

Stackblitz Here

Another way is to use NPM Package : ngx-pagination

Step 1:run the below command over terminal

npm install ngx-pagination --save

Step 2: Read data form Service

export class AppComponent implements OnInit {

 public products: any[] = [];
 constructor(private _Products: ProductService) { }

 ngOnInit(): void {
   this._Products.getJSON().subscribe(response => {
     this.products = response.items;
   });
 }

}

Step 3: Import dependency in app.module.ts

import { NgxPaginationModule } from 'ngx-pagination';
@NgModule({
   declarations: [
       AppComponent
   ],
   imports: [
       BrowserModule,
       NgxPaginationModule --> this line
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }

Now let's have a look on the code inside app.module.ts where the ngx-pagination module has been imported

Step 4: Update view from app.component.html

<table class="table table-sm table-bordered">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of products  | paginate:{itemsPerPage: 5, currentPage:p}">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
        </tr>
    </tbody>
</table>
<pagination-controls (pageChange)="p=$event"></pagination-controls>

Step 5: Run the app Run the app over the terminal with npm start

Stackblitz Here

Upvotes: 5

Related Questions