In my Angular application, I have a function that takes user selections for various filter types and sends a request to the API to retrieve filtered data based on those selections. Each filter type returns values in an array format, allowing users to select multiple options. For example, if a user selects "New York" and "Los Angeles" for the "location" filter, the result would be:
location: ['New York', 'Los Angeles']
The filter selections are passed into the component as follows:
<div class="page-content">
<table-display [records]="records"
(sendLocation)="onFilterReceived($event, type = 'location')"
(sendLanguage)="onFilterReceived($event, type = 'lan')">
</table-display>
</div>
To handle these filter selections, I've set up filters as an object to accommodate passing multiple values simultaneously. However, I'm encountering an issue where only one filter type value is persisted at a time, depending on the most recent change.
I'm looking for advice on how to update my code to ensure that both language and location filter values persist. Should I explicitly return the object, separate gathering of filter values into different functions, or consider another approach?
In essence, I need to pass the current filter selections for BOTH language and location rather than just one at a time.
private onFilterReceived(value: any, type: string) {
let filtersObj = {
language: '',
location: ''
};
if (value && type === 'lan') {
filtersObj.language = value;
} else if (value && type === 'location') {
filtersObj.location = value;
}
console.log('filtersObj: ', filtersObj);
// TODO Later: Collect all filter values and pass to API for filtered data
}
Currently, when a user selects 'Spanish' from the language filter, the console shows:
filtersObj: {language: Array(1), location: ""}
If the user then chooses 'New York' from the location filter, the language value is replaced, resulting in:
filtersObj: {language: "", location: Array(1)}
It's evident that only one filter value is stored at a time. How can I ensure that both language and location values are retained?