Given your getUsers function that retrieves the user data from a service and populates the users array, you can adapt it to work with the filtering and pagination based on your specific needs.
Here’s how to integrate the filtering and pagination logic with your existing getUsers method:
Modified Component Class
Let's modify your component code to include the necessary logic for filtering as well as managing pagination.
import { Component, OnInit } from '@angular/core';
import { OrdersService } from './orders.service'; // Update the import path as necessary
import { SharedService } from './shared.service'; // Update the import path as necessary
import { ToastrService } from 'ngx-toastr'; // Update the import path as necessary
@Component({
selector: 'app-user-list',
templateUrl: './user-list.component.html',
styleUrls: ['./user-list.component.css']
})
export class UserListComponent implements OnInit {
users: any[] = []; // Original user data
filteredUsers: any[] = []; // Filtered user data based on search
searchedKeyword: string = '';
itemsPerPage: number = 3;
p: number = 1; // Current page number
userTable: boolean = false;
showPagination: boolean = false;
constructor(
private OrdersService: OrdersService,
private sharedService: SharedService,
private toastr: ToastrService
) {}
ngOnInit() {
this.getUsers(); // Fetch users when component initializes
}
getUsers() {
this.sharedService.showLoader();
this.userTable = true;
this.OrdersService.getUsers().subscribe(
(data: any) => {
this.users = data.users; // Assuming data.users is an array of user objects
this.filteredUsers = this.users; // Initialize filteredUsers
this.userTable = true;
this.showPagination = true;
this.sharedService.hideLoader();
},
(err) => {
if (err.status === 401) {
this.toastr.error('Your session has expired!', 'Failed', {
enableHtml: true,
});
} else {
this.toastr.error(err.message, 'Failed');
}
this.sharedService.hideLoader();
}
);
}
filterUsers() {
if (this.searchedKeyword) {
this.filteredUsers = this.users.filter(user => {
return Object.keys(user).some(key =>
typeof user[key] === 'string' &&
user[key].toLowerCase().includes(this.searchedKeyword.toLowerCase())
);
});
} else {
this.filteredUsers = this.users; // Reset if no search input
}
this.p = 1; // Reset to first page on new search
}
// Getter for paginated users, to slice the filtered users based on current page
get paginatedUsers() {
const startIndex = (this.p - 1) * this.itemsPerPage;
return this.filteredUsers.slice(startIndex, startIndex + this.itemsPerPage);
}
get totalItems() {
return this.filteredUsers.length; // Total items for pagination
}
// This method will be called when the user types in the search input
onSearchInputChange() {
this.filterUsers();
}
// If you want to trigger the search on the Enter key as well
getUsersOnEnter() {
this.onSearchInputChange();
}
}
Updated Template (user-list.component.html)
Make sure your template is updated to bind the search input and call the new method:
<input
[(ngModel)]="searchedKeyword"
(input)="onSearchInputChange()" <!-- Call the filter method on input change -->
(keyup.enter)="getUsersOnEnter()" <!-- Optional: Trigger search on Enter -->
class="form-control adminPanel_searchInput vf_customInput"
name="searchTerm"
placeholder="Search for User .."
type="text" />
<table>
<tr *ngFor="let user of paginatedUsers">
<td>{{ user.name }}</td>
</tr>
</table>
<!-- Sample pagination controls -->
<pagination-controls (pageChange)="p = $event"></pagination-controls>
<!-- Optionally show the total results count or other UI elements -->
<div *ngIf="showPagination">
<p>Showing {{ paginatedUsers.length }} of {{ totalItems }} users</p>
</div>
<!-- Table can include headers and any other relevant UI -->
Explanation of Changes:
-
getUsers Method: This method pulls the user data from the service and populates both users and filteredUsers. It initializes filteredUsers with users upon a successful fetch.
-
filterUsers Method: This method filters the list of users based on the searchedKeyword. It is called automatically on each input change, ensuring that the displayed results are updated in real-time.
-
Pagination Management: The paginatedUsers are calculated on the fly based on the filtered list and current page (p). It slices the filteredUsers array to show only the items for the current page.
-
Template Updates: The bindings for the search input trigger filtering as the user types, ensuring a seamless search experience. The optional handling for pressing Enter can be kept or removed based on requirements.
Note on Pagination:
Ensure you have integrated pagination logic or a library (like ngx-pagination) if you haven't already. This example assumes you have a pagination control set that emits page changes. Replace pagination-controls and its logic based on what you are using in your project.
This setup ensures that you can search through all users, and filter results will be paginated correctly based on the search criteria while being updated in real-time.