Trigger a new GET request in Angular whenever a selection is made

I have a dilemma with my two select options. The first select allows you to choose different car brands, while the second select dynamically populates specific models based on the selected brand using a GET request.

component.html

  <mat-form-field appearance="fill">
    <mat-label>Brand</mat-label>
    <mat-select multiple formControlName="Brand" (selectionChange)="getModels($event)">
      <mat-option *ngFor="let item of vehicles" [value]="item">{{item}}</mat-option>
    </mat-select>
  </mat-form-field>

  <mat-form-field appearance="fill">
    <mat-label>Model</mat-label>
    <mat-select multiple formControlName="VehicleCategory">
      <mat-option *ngFor="let item of inputValue" [value]="item">{{item}}</mat-option>
    </mat-select>
  </mat-form-field>

The API call in the code above uses commas to separate each selected brand like this:

http://localhost:5001/api/Vehicle/Brands/BENTLEY,DACIA,AUDI,HONDA/Models 

Here's the implemented logic for that functionality:

component.ts

  getModels(form) {
        // retrieve models
        this.inputValue = this.newCampaignForm.get("Brand").value;
        this.campaignService.getModels(this.inputValue).subscribe((data: any[])=>{
          this.inputValue = data;
        });
  }

service.ts

    public getModels(inputValue: string){
    return this.http.get(this.API_SERVER + '/Vehicle' + '/Brands' + '/' + inputValue + '/Models');
  }

My goal is to trigger a new API call each time an option is selected without using commas, resulting in individual calls like these:

http://localhost:5001/api/Vehicle/Brands/OPEL/Models

http://localhost:5001/api/Vehicle/Brands/BMW/Models

Answer №1

To properly handle your selection, you must iterate through it

 getModels(event: any) {
    let value = event.value;
    value.forEach((item: any) => {
       console.log(item);
       this.campaignService.getModels(item).subscribe((data: any[]) => {
           this.inputValue = [...this.inputValue, ...data];
       });
    });
  }

This will allow you to pass a single brand to your service.

View an example on Stackblitz: https://stackblitz.com/edit/angular-sqkbdp-fx49j4?file=src%2Fapp%2Fselect-multiple-example.ts

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

Building a personalized command-line interface (CLI) tool using Typescript

I recently created a Typescript program that converts various .json file formats. However, I realized that I have hardcoded the file path for reading. const file = readFileSync('./name_of_file_path.json', 'utf-8'); // fixed file path. f ...

Errors occur when attempting to parse Uint8Array in Typescript

I received the following object as a response from calling the AWS Lambda client in NodeJS. { '$metadata': { httpStatusCode: 200, requestId: '1245', extendedRequestId: undefined, cfId: undefined, attempts: 1, tot ...

Transferring information between screens in Ionic 5

Looking for a way to transfer data between pages in Ionic 5. I'm currently working with Ionic version '5.4.16' and Angular version '10.0.8'. Can anyone suggest a method to achieve this? ...

Exporting a module from a TypeScript definition file allows for seamless sharing

I am in the process of developing a definition file for the Vogels library, which serves as a wrapper for the AWS SDK and includes a property that exports the entire AWS SDK. declare module "vogels" { import AWS = require('aws-sdk'); export ...

What is the best way to store numerous objects in an array at once?

Upon clicking the save button, I encounter this object: {description: "ghhg", dateSelected: "2020-02-27", startDate: "2020-02-27", company_id: "2", hr_id: 72, …} However, every time I click on save, a new object ...

Managing refresh events in Angular with F5 Key

Recently, I encountered an issue with my Angular project. During development (using ng s), everything functions normally and upon pressing F5, the page reloads correctly and works fine. However, when I build and deploy the project to a remote server, all ...

What is the process of creating the /dist folder in an unreleased version of an npm package?

Currently working on implementing a pull request for this module: https://github.com/echoulen/react-pull-to-refresh ... It seems that the published module generates the /dist folder in the package.json prepublish npm script. I have my local version of the ...

Connecting Angular CLI with the .NET Angular template: A step-by-step guide

Having decided to work with ASP.NET Core MVC, I've opted for the Angular template for the front-end (Check out the image below). Now, I'm looking at integrating the Angular Cli to efficiently manage components, directives, and more. How can I cus ...

The Node.js application is having trouble connecting to the Angular application on port 3000 when the Angular app is hosted on a remote machine

I'm facing an issue with my Nodejs app not being able to connect with the Angular app on port 3000 when the Angular app is hosted on a remote machine. However, everything works fine when both apps (Nodejs and Angular) are hosted on the same machine. C ...

Having difficulty retrieving the user list from Firebase within Angular 6

I am facing an issue with retrieving the list of users from Firebase. Despite having values already set in the database, I am getting empty arrays. The strange thing is that I can successfully add users to the Firebase database and retrieve the list of us ...

I'm struggling to transfer information from my form to TypeScript in Angular

Currently, I am working on developing a fullstack application using Node.js and Angular (material UI). However, I have encountered an issue that I need help with. I am trying to figure out how to retrieve data from an Angular form for a small web resource ...

Why am I restricted to adjusting mat-elevation settings within the component's CSS exclusively?

In my Angular 8 project, I am utilizing Angular material to enhance the design of my material cards. To set up the shadow effect on these cards, I am using the elevation helper mixins provided in the documentation: https://material.angular.io/guide/elevati ...

How to detach functions in JavaScript while preserving their context?

Can functions in JavaScript be detached while still retaining access to their context? For instance, let's say we have an instance of ViewportScroller called vc. We can retrieve the current scroll position with the following method: vc.getScrollPosi ...

Mastering Firebase pagination with RxJS - the ultimate solution

I came across this helpful post on Cloud Firestore pagination with RXJS at Cloud Firestore - How to paginate data with RXJS While it is exactly what I need, I am struggling to understand how to implement the following code snippet: import { UsersService } ...

unable to fetch the value from the array

My goal is to display the elements from my address table in a table format, but I am facing difficulties. Below is what I see in my console: {…} ​ "-LsMm5EeM0DavWwNweBc": Object { adress: "njkbj", city: "Marcory", name: "jjbjkb,", … } ​ "-LsMmBCOH ...

A step-by-step guide to showcasing dates in HTML with Angular

I have set up two datepickers in my HTML file using bootstrap and I am attempting to display a message that shows the period between the first selected date and the second selected date. The typescript class is as follows: export class Datepicker { ...

Arrange an array in JavaScript according to the value of its keys

I am looking to rearrange an array of Objects with status 'Pass' & 'Fail'. I want to move all Fail ones to the top and Pass ones to the bottom. Is there a specific array method that can help achieve this? let a = [ { name: 'x&apo ...

Tips for extracting individual fields from a payload in Angular 8

How do I extract individual fields from the payload and bind them with HTML on a page? I am trying to retrieve the alphacode and countryname in Angular 8. This is my Component: this.table$ = this.productService.get(id) .map(actions => { c ...

Error: Model attribute missing in Adonis JS v5 relationship

Recently, I started diving into the Adonis framework (v5) and decided to build a todo list api as part of my learning process. However, I'm facing an issue concerning the relationship between the User and Todo entities. Let me show you the models fo ...

Why is there no type guard for Number.isFinite()?

Why doesn't Number.isFinite have a type guard like number is number? This example triggers an error Object is possibly 'undefined' function inc (n?: number) { return Number.isFinite(n) ? n + 1 : 1; } Check it out on the Playground: http ...