Transmitting Filter Choices as an Object for Retrieving Multiple Values within an Angular Application

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?

Answer №1

To unlock the potential of your code, harness the power of the this keyword. Begin by setting your component filters to empty strings, enabling your initial API request to retrieve all data:

selectedLanguage: any = '';
selectedLocation: any = '';
selectedZipcode: any = '';
selectedBranch: any = '';

Next, update your onFilterReceived() method as follows:

private onFilterReceived(value: any, type: string) {
    if (value && type === 'lan') {
        this.selectedLanguage = value;
    }
    else if (value && type === 'location') {
        this.selectedLocation = value;
    }

    console.log('filterSelections: ', {language: this.selectedLanguage, location: this.selectedLocation});
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The property functions normally outside the promise, but is undefined when within the promise context

I am currently working on filtering an array based on another array of different objects but with the same key field. Although I have made some progress, I keep encountering errors that I am unable to resolve. @Component({ selector: 'equipment&ap ...

Can you please provide guidance on how to dynamically add number values from an array to a select tag in Vue.js?

I'm trying to populate a select tag with options from an array variable that contains arrays of number values. However, the values being output appear to be blank. Here is the HTML code: <select required id="dropDown"> <option>Sele ...

What might be causing the delay in synchronization between the state in my parent component?

import React, { Component } from "react"; import "./Game.css"; class Game extends Component { static defaultProps = { list: ["rock", "paper", "scissors"] }; constructor(props) { super(props); this.state = { play: false, rando ...

Troubleshooting the ngcc error in StackBlitz when using MatTableModule from Material Design

Upon comparing my project config with this sample, I am puzzled by the error message that keeps popping up: An error in turbo_modules/@angular/[email protected]/table/table-module.d.ts (8:22) It seems that MaterialModule is trying to export something ...

Learn how to extract substrings from a variable within an API using Vue.js

Exploring VueJs for the first time and looking to split a string by comma (,) retrieved from an API into separate variables. The data is coming from a JSON server. "featured-property": [ { "id": "1", " ...

Responsive images in CSS3/HTML5 are designed to adapt to different

I am looking to implement responsive image sizing based on the webpage size. My images come in two different sizes: <img src="images/img1.jpg" data-big="images/img1.jpg" data-small="images/img1small.jpg" alt=""></img> The data-small image has ...

What is the best way to efficiently loop through elements and add them to a new array in JavaScript while optimizing performance?

Here's the code in question: let newArr = [] const items = [ { name: 'JTB 0110-01', offers: ['one', 'two'] }, { name: 'LOBA CHEMIE', offers: ['three', &apos ...

Why does Chrome keep retrieving an outdated JavaScript file?

Lately, I've been facing a frustrating issue that I just can't seem to figure out. Every now and then, when I update the JavaScript or CSS files for my website hosted on Siteground, Chrome simply refuses to acknowledge the changes. While other br ...

It is not possible to access an object's properties using bracket notation when the index is a variable

Is there a way to convert the JavaScript code below into TypeScript? function getProperties(obj) { for (let key in obj) { if (obj.hasOwnProperty(key)) { console.log(obj[key]); } } } I've been trying to find a solution but it seems t ...

Customize numbers in JavaScript with a Unity-inspired design changer

I am currently working on implementing a number input feature that allows users to adjust values by clicking and holding the mouse button while moving the cursor left and right, similar to Unity's editor number adjuster: https://youtu.be/uY9PAcNMu8s?t ...

bootstrap 4 - logo in navbar brand stays the same even when scrolling

I integrated Bootstrap 4 and successfully created a navbar. However, I am encountering a conflict when trying to change the navbar logo upon scrolling down. Despite my efforts, it is not functioning as expected. Does anyone know how to resolve this issue? ...

Content Mismatch: The webpage was accessed through a secure HTTPS connection, but a request was made for an unsecured resource. Access to this content has been denied as

Error: Mixed Content. The webpage at '' was accessed using HTTPS, but it tried to load an insecure resource ''. This request was blocked as the content needs to be served over a secure connection (HTTPS). ...

Dynamically size and position elements to fit perfectly within the container

I am currently facing a challenge with my absolutely positioned elements that have different position.top and height values generated from the database. The main goal is to resolve collisions between these elements by shifting them to the right while adju ...

Is a specific format necessary for express next(err) to function properly?

Recently, while working on my express sub app that utilizes the http-errors module, I encountered an interesting issue. When passing new Forbidden() to the next() callback, it seemed to vanish without triggering any callbacks. However, passing new Error() ...

The module cannot be located due to an error: Package path ./dist/style.css is not being exported from the package

I am facing an issue with importing CSS from a public library built with Vite. When I try to import the CSS using: import 'rd-component/dist/style.css'; I encounter an error during the project build process: ERROR in ./src/page/photo/gen/GenPhot ...

Associate an alternate attribute that is not displayed in the HTML component

Imagine there is a collection of objects like - var options = [{ id: "1", name: "option1" }, { id: "2", name: "option2" } ]; The following code snippet is used to search through the list of options and assign the selected option to anot ...

How can we eliminate duplicate objects in a JavaScript array by comparing their object keys?

I am trying to remove duplicate objects from an Array. For example, the object 'bison' appears twice. var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ...

In Vue.js, it is not possible to modify a component variable within a callback function

I have implemented a custom Login.vue component using vue.js to allow users to log in to my application through AWS Cognito. The authentication process is handled by the ___.authenticateUser() method, which initiates a session with Cognito. Below is the co ...

Tips for Implementing Cache Busting in Angular Universal

Is there a way to execute cache busting in Angular Universal? I attempted to run the command npm run build:ssr --output-hashing=all but it did not make any changes. PACKAGE.json "scripts": { "ng": "ng", "start": "ng serve", "build": "ng bui ...

Testing React Components - The `useClient` function should only be used within the `WagmiConfig` component

In my Next.js app with TypeScript, Jest, and React testing library, I encountered an error while trying to test a component. The error message states that `useClient` must be used within `WagmiConfig`. This issue arises because the `useAccount` hook relies ...