Modify the selection in one dropdown menu based on the selection in another dropdown menu using Angular 8

When I have two dropdowns, I aim to update the second dropdown with a matching JSON object based on the value selected in the first dropdown.

JSON

 this.dropdownValues = {
"mysql 8": {
    "flavor": [
        "medium",
        "small",
        "large"
    ],
    "version": "mysql 8"
},
"mysql 5.7": {
    "flavor": [
        "small",
        "medium"
        
    ],
    "version": "mysql 5.7"
}
}

This JSON displays version values in the first dropdown. Upon changing the selection in the first dropdown, I want the second dropdown to show the related flavor array. For example, if I select "mysql 5.7," then the second dropdown should display "small" and "medium" as flavor options.

In Angular 8, how can I achieve this functionality? While I am able to populate the dropdown values in my HTML page, I am uncertain about how to retrieve the flavor value when the selected version matches.

Answer №1

View Demo Utilize the (change) event to detect changes in your Angular application.

Let's consider an example with two select elements:

<select [(ngModel)]="sqlVersion" (change)="onChange()">
  <option value="-1">Choose Version</option>
  <option *ngFor="let el of versions" value="{{el}}">{{el}}</option>
</select>
<select [(ngModel)]="choosenFlavor">
  <option value="-1">Choose Flavor</option>
    <option *ngFor="let ver of flavors" value="{{ver}}">{{ver}}</option>
</select>

Add a change event to the first select element, and then update the array of options for the second select element in the component file.

sqlVersion = "-1";
flavors = [];
choosenFlavor = "-1";
versions = [];
dropdownValues = {
    "mysql 8": {
        "flavor": [
            "medium",
            "small",
            "large"
        ],
        "version": "mysql 8"
    },
    "mysql 5.7": {
        "flavor": [
            "small",
            "medium"    
        ],
        "version": "mysql 5.7"
    }
}
constructor() {
    this.versions = Object.keys(this.dropdownValues);
}
onChange() {
    this.choosenFlavor = '-1';
    if (this.sqlVersion == "-1") {
        this.flavors = [];
        return;
    }
    this.flavors = this.dropdownValues[this.sqlVersion].flavor;
}

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

Storing data retrieved from MongoDB into a local array in a MEAN stack

I am currently working on a small application using the MEAN stack. I have saved some user details in MongoDB and now I want to retrieve and store only the email ids in a local array. The fetching part is working well, but I'm facing issues with savin ...

Determine the full location information with the help of Google Maps SDK without the need

My current challenge involves dealing with a list of unformatted and incorrectly written addresses. I am seeking a way to iterate through these flawed strings and generate more organized and accurate addresses using one of the many Google Maps SDKs availa ...

Sending template reference from one Angular component to another

I have a main grid component that includes smaller grid-item components. The majority of these grid items navigate to a specific route when clicked. However, there is one particular item that should open a modal window instead of navigating. Is there a wa ...

What is the best way to pass dynamic values to a service constructor from a component?

After days of attempting to grasp 'the Angular paradigm', I still find myself struggling to understand something about services that are not singletons. It seems impossible for me to pass a runtime-determined value to a service constructor, as I ...

Identify the general type according to a boolean property for a React element

Currently, I am facing a scenario where I need to handle two different cases using the same component depending on a boolean value. The technologies I am working with include React, Typescript, and Formik. In one case, I have a simple select box where th ...

Organizing Angular and Express Files

I've been researching the best way to structure Angular and Express, reading numerous articles and posts on the topic. Now I'm left wondering - should I share the same node_modules folder for both Angular and Express, or keep them separate? My c ...

The contents table remains fixed in the top right corner as you scroll

I have developed an Angular app with a table-of-contents component that only displays two items. The code for the script is as follows: ts import { Component, OnInit } from '@angular/core'; import { pdfDefaultOptions } from 'ngx-extended-p ...

Having trouble getting undefined values for keys while attempting to retrieve all the data from Firebase DB with Angular

Currently, I have code that is fetching records from the Firebase database using both Angular and Ionic. The code functions properly, but it does not provide me with the keys for each record. Instead, it returns 'undefined'. I have researched s ...

Patience is key as we anticipate the parent component/module loading the data

Just a note: I am aware of the existence of APP_INITIALIZER, but it appears to only work in the top-level module (app.module.ts) of the application. I have a parent component that loads some data: In admin-area.component.ts: ngOnInit(): void { forkJo ...

Press the damaged interior when looping through array elements in *ngFor, especially if they are generated from a function

When working with Plnkr, I encountered a peculiar edge case that seems to be related to the usage of pixijs or webgl. Interestingly, clicking on elements in the list works fine until you interact with pixijs by clicking the button, after which the click ev ...

Navigating to a Different Page in Angular 7

After logging in on my login page, the dashboard component appears below the login page instead of redirecting as a new page. How can I achieve this in Angular 7? Any assistance would be greatly appreciated. Thank you! app.component.ts import { Component ...

Issue: NG04002 encountered post migration from Angular to Angular Universal

Having recently created a new Angular app and converted it to Angular Universal, I encountered an issue when running the project using npm run dev:ssr. The error displayed in the terminal is as follows: ERROR Error: Uncaught (in promise): Error: NG04002 Er ...

The z-index overlapping problem in webkit browsers is a result of Angular 7 animations

I have implemented staggered animations in my Angular 7 application to bring elements to life upon page load. However, I am facing a strange z-index problem with one of my components. Here is the animation code: @Component({ selector: 'track-page& ...

Setting a default value and object ID in Angular's reactive forms for a select dropdown

Having an issue with validating a default value in a selector that serves as a message to select an option. The problem arises from the validation of this option, as it is linked to the object ID of another collection in the database (mongoose-express js). ...

Generate a fresh class instance in Typescript by using an existing class instance as the base

If I have these two classes: class MyTypeOne { constructor( public one = '', public two = '') {} } class MyTypeTwo extends MyTypeOne { constructor( one = '', two = '', public three ...

Troubleshooting image upload issues with AWS S3 in Next.js version 13

I encountered a consistent problem with using the AWS SDK in NextJS to upload images. I keep getting error code 403 (Forbidden). Could there be other reasons why this error is occurring besides the accessKeyId and secretAccessKey being invalid? Below is my ...

An error in npm occurred: "The name "@types/handlebars" is invalid."

While attempting to install typedoc using npm, I encountered the following error: npm ERR! Invalid name: "@types/handlebars" To resolve this issue, I proceeded to install @types/handlebars directly by running: npm install @types/handlebars However, I r ...

How to attach an event listener to an input element using Angular

I am looking to add a listener to an input element that will be triggered every time the user changes the input values. The goal is to display the current values chosen by the user. Example HTML template: <div id="idDoseLabel1" class="da ...

What is the best way to pass props to a styled component (e.g., Button) in Material-UI

One of my tasks involves creating a customized button by utilizing the Button component with styled components. export const CustomButton = styled(Button)({ borderRadius: "17px", fontWeight: 300, fontSize: ".8125rem", height: &q ...

Using NextJS to execute a Typescript script on the server

I am working on a NextJS/Typescript project where I need to implement a CLI script for processing files on the server. However, I am facing difficulties in getting the script to run successfully. Here is an example of the script src/cli.ts: console.log(" ...