Using Typescript to update a dropdown menu based on the selected date

I'm in the process of developing a menu that begins with the user selecting a date, followed by choosing an option from a dropdown menu.

The dropdown menu values are fetched from a database using an API call, which is functioning properly. However, these options are dynamic and change based on the selected date. My challenge lies in finding a way to trigger the API call ('getOptions' -> for fetching the list of values) once the user picks a date.

Any guidance on this matter would be greatly appreciated. Below is the code snippet. Thank you!

HTML

            <div class="row">
                <div class="col-md-4">
                    <p class="word">Date:</p> 
                </div>
                <div class="col-md-8">
                    <input class="form-control" type="date" id="start" name="trip-start" [(ngModel)]=selectedDate>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <p class="word">Options:</p> 
                </div>
                <div class="col-md-8">
                    <select name="Template" class="form-control">
                        <option>- -Select Template- -</option>
                        <option *ngFor="let x of optionsAvailable">{{ x.Value }}</option>
                    </select>
                </div>
            </div>

TS

  selectedDate = '';
  optionsAvailable: any = {};

  constructor(
    private commonService: CommonService
  ) { }

  ngOnInit() {
  }

  getOptions() {
    this.commonService.getOptions(this.selectedDate).subscribe(
      data =>  {
        this.optionsAvailable= [];
        for (let x = 0; x < data['data'].length; x++) {
          this.optionsAvailable.push({
            Id: data['data'][x][0],
            Value: data['data'][x][1]
          });
        }
      },
    );
  }

Answer №1

I didn't have enough time to confirm if this solution actually works, but it should provide a good understanding of the concept:

this.form.get("date").valueChanges
.pipe(
    switchMap(() => this.commonService.getOptions(this.selectedDate))
)
.subscribe(data =>  {
    this.optionsAvailable= [];

    for (let x = 0; x < data['data'].length; x++) {
      this.optionsAvailable.push({
        Id: data['data'][x][0],
        Value: data['data'][x][1]
      });
    }
 });

Essentially, by using valueChanges on your date selector, the resulting observable will trigger a value on each date selection, prompting the switchMap to retrieve backend data accordingly.

Although untested, this approach outlines a potential solution for this situation.

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

What is the best way to add items to arrays with matching titles?

I am currently working on a form that allows for the creation of duplicate sections. After submitting the form, it generates one large object. To better organize the data and make it compatible with my API, I am developing a filter function to group the du ...

What are the steps to making request and response models in Angular?

Exploring the best approach for handling request and response models in Angular prompts the question of whether we should always create separate models for GET and POST operations, or if utilizing keywords like partial could offer a solution. For example, ...

Encountering a CORS error specifically when adding an Auth0 token to the request on the API gateway

I'm currently working on hosting a full stack web application in AWS. The setup involves an Angular frontend stored in an S3 bucket behind CloudFront, using a domain from Route53. On the backend, there's a TypeScript Express project behind API Ga ...

Why is my Angular Material 2 fab button not floating and instead scrolling with the content?

<button md-fab></button> The Angular material button does not remain sticky even when I position it fixed. It scrolls with the content instead. I attempted to add a class and used the following CSS: .fltBtn{ position:fixed; right:30p ...

Uncovering TypeScript's Type Inference Power Through the keyof Keyword

Recently, I encountered a situation where I needed to utilize an abstract class. export abstract class ABaseModel { public static isKeyOf<T>(propName: (keyof T)): string { return propName; } } Following that, I also created another class wh ...

Creating a randomly generated array within a Reactjs application

Every time a user clicks a button in reactjs, I want to create a random array of a specific size. The code for generating the array looks like this: const generateArray = (arraySize: number): number[] => { return [...Array(arraySize)].map(() => ~~( ...

The karma test encounters difficulties in establishing a connection with the 'chrome' instance that has been launched

Currently, I am facing an issue with my Karma test running on a nodejs jenkins pod. npm is timing out when trying to connect to the Chrome instance on the selenium hub. Everything was working fine until yesterday without any changes made to the configura ...

Replacing children prop in React using Typescript 3.5 and above

I'm facing a scenario where I need to specifically define the type of child component in a React.FC, overriding the default React.ReactNode. The reason behind this is that I'm developing a small library, and I want compile-time errors to notify ...

Challenges with Angular's HTML select element

Upon initial page load, the first select option displays "select street" as seen in the links below. After selecting a city, the corresponding streets are shown in the first select. However, the issue arises when choosing a street and then selecting anoth ...

Custom Error Page Implementation in Angular and Spring Boot

I keep running into a Whitelabel Error Page (error 404) whenever I attempt to access any page on my Angular 9 application, except for the root route. Interestingly, using the page buttons within the Angular router functions perfectly fine. Despite trying ...

Adding a line break ( ) in a paragraph within a TypeScript file and then transferring it to HTML does not seem to be functioning properly

Angular Website Component: HTML file <content-section [text]="data"></content-section> TypeScript file data = `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's stand ...

Angular8 Material Grid displaying headers and tiles, experiencing slight resizing issue with mat-grid-tile content

Exploring Angular8 Material: Grid Layout with Headers and Tiles Currently, I am delving into the workings of the grid system within Angular Material. I am dynamically fetching components and organizing them within a grid. While the grid list and tiles are ...

Utilize Angular Service Worker to prefetch API data efficiently (dataGroups)

I am working on an Angular website that needs to function offline. In order to achieve this, I need some data from the API, which can be considered Stale data. To handle this scenario, my approach is to first attempt to retrieve the data from the API, and ...

Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh. Below is the code snippet I am currently ...

Bootstrap causing issues with correct display of div element

I'm having trouble getting my divs to display on the same row. It seems like when I have 2 rows, the button is positioned correctly. However, with only one row, the button ends up on the second row. Here is the current layout: https://i.sstatic.net/L ...

What is the best way to implement react-password-checklist with zod?

I've been trying to utilize the react-password-checklist library to inform users if their password complies with the rules set in zod's schemaUser. However, I'm facing challenges in implementing this feature successfully. Note: I am using zo ...

Is there a method for converting an Angular2 component into a string format?

Is it possible to leverage Angular2 template syntax when creating a Google Maps InfoWindow? My understanding is that this involves passing a component as a template string to the content property in the constructor object of the InfoWindow. If my assumpt ...

Retrieving the status of an ngForm in the parent component

Here is the Main HTML Code: <main-component> <inner-element></inner-element> <button type="submit" [disabled]="!innerElementForm.valid"> </main-component> Below is the Sub Element HTML Code: <inner-element> ...

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 ...

The output type of a function given an input

Essentially, I have successfully rendered a return type for my combined reducers using the following code: const rootReducer = combineReducers({ notes: notesReducer, categories: categoriesReducer, flyout: flyoutReducer // more reducers }); export ...