Having a table with pagination, I created a function that filters the object and displays the result in the table.
The issue arises when I perform a new search. The data from the initial search gets removed and cannot be found in subsequent searches.
Below is the code snippet for my sort function:
export class TaxreportsComponent implements OnInit {
public taxList: Array<Tax>;
public page: number;
public currentPage: Array<Tax>;
public totalItems: number;
constructor(private service: CompanyService) {
this.totalItems = 0;
this.currentPage = [];
this.taxList = [];
this.page = 1;
}
ngOnInit() {
this.service.getTaxList((data) => this.onGetTaxList(data));
}
onGetTaxList(data) {
this.taxList = data;
this.currentPage = this.taxList.slice(0, 10);
this.totalItems = this.taxList.length;
}
pageChanged(event) {
const startItem = (event.page - 1) * event.itemsPerPage;
const endItem = event.page * event.itemsPerPage;
this.currentPage = this.taxList.slice(startItem, endItem);
}
// Sort the data and update the table
sort(searchWord) {
const data = this.taxList.filter(item => {
return item.type === searchWord;
});
this.onGetTaxList(data);
}
Here is the HTML code:
<app-home-menu (filteEvent)="sort($event)" ></app-home-menu>
<div class="table-container">
<table class="table">
<thead>
<tr class="table-nav">
<th scope="col">Year</th>
<th scope="col">Type</th>
<th scope="col">HP</th>
<th scope="col">CompanyName</th>
</tr>
</thead>
<tbody>
<ng-container *ngFor="let tax of currentPage">
<tr>
<td>{{tax.year}}</td>
<td>{{tax.type}}</td>
<td>{{tax.cid}}</td>
<td>{{tax.company}}</td>
</tr>
</ng-container>
</tbody>
</table>
<div class="table-footer">
<pagination class="pagination" nextText=">" previousText="<" [totalItems]="totalItems" (pageChanged)="pageChanged($event)"> </pagination>
</div>
</div>
It is essential to initialize the original object before each new search. I need to find a solution for this.