Hackerrank Paginated Football Competitions Angular intermedialte certification Solution

Priti Jha
2 min readJan 2, 2024

--

Creating a paginated list of football competitions using Angular typically involves fetching data from an API and displaying it in a paginated manner. Below is a simple example using Angular with Angular Material for pagination:

you can create a simple pagination component in Angular without any external libraries. Below is an example:

ng generate component football-competitions

Update the football-competitions.component.ts file with the following code:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

interface Competition {
id: number;
name: string;
winner: string;
year: string
}

@Component({
selector: 'app-football-competitions',
templateUrl: './football-competitions.component.html',
styleUrls: ['./football-competitions.component.css']
})
export class FootballCompetitionsComponent implements OnInit {
competitions: Competition[] = [];
pageSize = 10;
currentPage = 1;
totalItems = 0;

constructor(private http: HttpClient) { }

ngOnInit(): void {
this.loadCompetitions();
}

loadCompetitions(): void {
const apiUrl = `${apiUrl}${currentPage}`; // Replace with your API endpoint

this.http.get<any>(apiUrl).subscribe(response => {
this.competitions = response.data;
this.totalPage = response.totalpage;
});
}

onPageChange(page: number): void {
this.currentPage = page;
this.loadCompetitions();
}

getPages(): number[] {
return Array.from({ length: totalPage }, (_, i) => i + 1);
}
}

Update the football-competitions.component.html file with the following code:

<h2>Football Competitions</h2>

<section class="pagination">
<button *ngFor="let page of getPages()" (click)="onPageChange(page)">
{{ page }}
</button>
</section>

<ul>
<li *ngFor="let competition of competitions">
{{ competition.name }} winner in {{competition.year}}
</li>
</ul>

Add the following styles in football-competitions.component.css:

.pagination {
display: flex;
margin-top: 10px;
}

.pagination button {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
}

.pagination button:hover {
background-color: #45a049;
}
  1. Replace the placeholder API endpoint in the loadCompetitions method with a real API that provides football competition data.

This updated example should provide a basic pagination component without relying on Angular Material. Make sure to replace the API endpoint and adjust the code based on your specific requirements.

--

--

Priti Jha
Priti Jha

Written by Priti Jha

Senior front-end developer writing about Angular 8 , Ionic Framework ,Javascript, HTML, Css and all front end technology.

Responses (1)