In this tutorial, you will learn how to implement sorting, pagination, searching and filtering in an Angular application. We would be using NgBootstrap (Angular Powered Bootstrap). You will learn how to get list of countries for public REST APIs. Then display on a HTML table using Angular.
This would be a step by step tutorial. We would be using a free REST API for countries list available here – https://restcountries.com/v3.1/all
- Create the Angular Component
- Create the Country Interface
- Function to Fetch List of Countries
- Function to Load… and Refresh…
- The Final HTML Page
1. Create a new Angular Component
We would have to create a new Angular component that would display the list of countries. Follow the steps
Step 1 – Create a new component. I call it rest-country
Step 2 – Install the following dependencies, ng-bootstrap like so
ng add @ng-bootstrap/ng-bootstrap
Step 3 – Create a HttpClient variable as a parameter to the constructor.
2. Create the Country Interface
We would have to fetch list of countries from an external rest api. Since we would not be using all the fields, we would need to create an interface containing only the fields we need. Place this just after the imports statements.
interface Country { name: string, capital: string, population: number, area: number, flag: string, continent: string[] }
3. Function to Get List of Countries
Now, we would write the function to retrieve a list of countries.
getCountries(): any{ return this.httpClient.get<Country[]>('https://restcountries.com/v3.1/all').pipe( map((response:any) => { return response.map(e => { return { flag: e.flags.png, name: e.name.common, capital: e.capital, population: e.population, area: e.area, continent: e.continents[0] }; }) }) ); }
You can do a console.log() to see that the list of countries is actually retrieved.
Then you also need to create a countries variable like so:
countries: Country[];
4. Write the Load.. and Refresh Functions
The load… function will execute once to fetch the list of countries. Then it would save this list to a local storage. The refresh… function will execute each time a pagination occurs in the table.
Step 1 – Initialize the variables
The variable would be as follows:
page = 1; //the initial page to display collectionSize = 250 //total number of countries in the list pageSize = 20; //size of the first page
Step 2 – Write the the refreshCountries() Function
The function is given below. Note that it gets the countryList from the localStorage where the loadCountries function added this variable.
refreshCountries(){ this.countries = JSON.parse(localStorage.getItem('countryList')) .map((country, i) => ({id: i + 1, ...country})) .slice((this.page - 1) * this.pageSize, (this.page - 1) * this.pageSize + this.pageSize); }
Step 3 – Write the loadCountries() Function
The loadCountries() function is given below. Notice that the after fetching the countries list, this function calls the refreshCountries() function. This is done to set the initial page and so the complete list is not loaded
loadCountries(){ this.getCountries().subscribe( (x) => { this.countries = x; localStorage.setItem('countryList', JSON.stringify(x)); this.refreshCountries(); // Display the first page }) }
Step 4 – You now need to call the loadCountries() function in the ngOnInit() method.
5. Work on the HTML Page
The complete page content is given below:
<div class="container" style="background-color: white; padding: 0px;"> <section class="content"> <div class="card"> <div class="card-header"> <h3 class="card-title">List of Countries</h3> <div class="card-tools"> <button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse"> <i class="fas fa-minus"></i> </button> <button type="button" class="btn btn-tool" data-card-widget="remove" title="Remove"> <i class="fas fa-times"></i> </button> </div> </div> <div class="card-body p-0"> <table class="table table-striped projects"> <thead> <tr> <th></th> <th style="width: 1%"> # </th> <th style="width: 20%"> Country </th> <th style="width: 20%"> Capital </th> <th style="width: 20%"> Population </th> <th style="width: 20%"> Area </th> <th style="width: 30%"> Continent </th> </tr> </thead> <tbody> <tr *ngFor="let country of countries; let i=index;"> <td>{{(i + 1) + (page - 1) * pageSize}}</td> <td> <img width="30px" height="15px" src={{country.flag}}> </td> <td> {{country.name}} </td> <td> {{country.capital}} </td> <td> {{country.population | number}} </td> <td> {{country.area | number}} </td> <td> {{country.continent}} </td> </tr> </tbody> </table> <hr> <div class="d-flex justify-content-between p-2"> <ngb-pagination [collectionSize]="collectionSize" [(page)]="page" [pageSize]="pageSize" (pageChange)="refreshCountries()"> </ngb-pagination> <select class="form-select" style="width: auto" [(ngModel)]="pageSize" (ngModelChange)="refreshCountries()"> <option [ngValue]="15">15 items per page</option> <option [ngValue]="20">20 items per page</option> <option [ngValue]="50">50 items per page</option> <option [ngValue]="100">100 items per page</option> <option [ngValue]="150">150 items per page</option> </select> </div> </div> </div> </section> </div>
At this point, you can start the application. Try to page across different pages. Also try to change the items per page. Make sure everything works perfectly well. Then in the next part, you will learn how to do sorting and paging.