Creating a list of checkboxes on a UI allows users to toggle and filter data results. To achieve this, I am storing the selected checkboxes as a string array. The structure of my code is outlined below:
export interface IMyObjectFromAPI {
status: {
id: number,
description: string,
location: string,
name: string,
imageUrl: string
}
}
var filteredByTerms: string[] = [];
var resultsFromAPI: IMyObjectFromAPI [] = [];
var filteredDataResults: IMyObjectFromAPI[] = [];
The API call results are saved in the resultsFromAPI
array for further processing.
In the user interface, there are multiple checkboxes based on countries populated through an array loop. Upon selecting a checkbox, the following function is triggered. The objective here is to apply multiple filters (such as location + name) to the filter terms array:
filterDataResults(term: string) {
var indexOfTerm = this.filteredByTerms.indexOf(term);
if (indexOfTerm === -1) {
this.filteredByTerms.push(term);
this.filteredDataResults = this.resultsFromAPI.filter(x => x.location ===
this.filteredByTerms.includes(term));
} else {
this.filteredByTerms.splice(indexOfTerm, 1);
this.filteredDataResults = this.resultsFromAPI.filter(x => x.location ===
this.filteredByTerms.includes(term));
}
}
I hope I have clarified the process adequately; however, a visual aid has been provided to assist. The layout consists of checkboxes on the left, the dataset on the right, and the ability for checkboxes to accumulate selections (as shown in the linked image).