How can I update a dropdown menu depending on the selection made in another dropdown using Angular

I am trying to dynamically change the options in one dropdown based on the selection made in another dropdown.

ts.file

     Countries: Array<any> = [
                { name: '1st of the month', states: [ {name: '16th of the month'} ] },
                { name: '2nd of the month', states: [ {name: '17th of the month'} ] },
                { name: '3rd of the month', states: [ {name: '18th of the month'} ] },
                             ]
    
     states: Array<any> = []; 
     cities: Array<any> = []; 
    
     changeCountry(country: any) { 
            this.states = this.Countries.find(cntry => cntry.name == country.target.value).states; 
        }

html.file

    <mat-form-field>
        <mat-select  [(ngModel)]="custFirst"  name="custFirst" placeholder="Country"  (change)="changeCountry($event)">
               <mat-option   *ngFor="let country of Countries" [value]="country.name" > {{ country.name }}</mat-option> 
         </mat-select>
    </mat-form-field>
            
    <mat-form-field>
          <mat-select placeholder="State">
             <mat-option *ngFor="let state of states"  [value]="state.name">{{ state.name }} 
             </mat-option>
           </mat-select>
    </mat-form-field>

I am facing an issue where the value in the second dropdown is not being updated as expected. Can someone please assist me in resolving why the trigger part is not working?

Answer №1

In order to update the state dropdown automatically, it is recommended to replace the change event with selectionChange. To achieve this, simply add [(ngModel)] to the state dropdown and ensure it gets updated when the country selection changes:

 changeCountry(country: any) { 
    this.states = this.Countries.find(
      (cntry) => cntry.name == country.value
    ).states;
    this.sFirst = this.states[0].name;
 }
<mat-form-field>
    <mat-select  [(ngModel)]="custFirst"  name="custFirst" placeholder="Country" (selectionChange)="changeCountry($event)">
           <mat-option   *ngFor="let country of Countries" [value]="country.name" > {{ country.name }}</mat-option> 
     </mat-select>
</mat-form-field>
        
<mat-form-field>
      <mat-select placeholder="State" [(ngModel)]="stateFirst">
         <mat-option *ngFor="let state of states"  [value]="state.name">{{ state.name }} 
         </mat-option>
       </mat-select>
</mat-form-field>

To see a working example, you can visit: https://stackblitz.com/edit/angular-6-stackoverflow-nzvqse?file=src/app/components/stackoverflow-solution/stackoverflow-solution.component.ts

Answer №2

To efficiently manage this scenario, implement switch case statements and provide the country value to the getStates function

country:string = 'Uruguay';
states:string[];

getStates(country: string){
   switch(country) {
      case '':
        this.states = [];
        break;
      case 'República Dominicana':
        this.states = ['', 'Azua', 'Baoruco', 'Barahona', 'Valverde'];
        break;
      case 'Uruguay':
        this.states = ['', 'Artigas', 'Canelones', 'Tacuarembó'];
        break;
      case 'Venezuela':
        this.states = ['', 'Amazonas', 'Apure', 'Yaracuy'];
        break;            
   }
}

this.getCountryData(this.country);

Next, in the view section:

 <mat-option *ngFor="let state of states"  [value]="state.name">{{ state.name }}

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

Enhanced User Experience Through Triggered Content Recommendations based on Scrolling Patterns

When a user scrolls beyond a certain point on a webpage, I would like a recommended content popup to slide out from the right side at the bottom of the page. An excellent example can be seen on USAToday where a blue recommended box appears as you scroll d ...

Dynamic Bootstrap Popover: Creating interactive popups by dynamically attaching events to buttons

I am looking to implement the Bootstrap Popover module to create a confirmation dialog for a delete action. When a <button> is clicked, instead of immediately executing a function, I want a popup to appear allowing the user to either confirm or dismi ...

Token does not function properly on Fetch request sent to PHP script

I have a pair of files: one is revealing a session token, while the other is responding to a javascript fetch. The first file goes like this: <?php session_start(); unset($_SESSION['sessionToken']); $_SESSION['sessionToken'] = vsprin ...

Loading intersecting objects with FBXLoader in Three.js

After successfully loading an fbx file using FBXLoader and adding it to the scene object, I encountered an issue where I couldn't interact with the object on click to apply transform controls. Interestingly, all other objects were clickable except for ...

What is the best way to show only the weekdays on the x-axis?

My goal is to create a scatter-linked graph using D3.js, showcasing the people count for various shifts on different dates in January 2020. Here is the code snippet I am working with: <!DOCTYPE html> <html lang="en" > <head> & ...

Running multiple instances of setTimeout() in JQuery

I'm looking for a way to delay the execution of 10 lines of independent jQuery code with 2 seconds between each line. I initially tried using setTimeout() on each line, but is there a more elegant solution for this scenario? The jQuery DELAY method do ...

Capturing numerous data points with JavaScript

<span> <label class="label">Color</label> <span class="foo"><input name="Color" value="Blue" class="customs" maxlength="100" type="text"/></span> </span> </span> <span> <label cla ...

Exploring the Power of ForkJoin in RXJS with Complex Data Structures

I'm looking for a solution using forkJoin to execute an array of objects containing key-value pairs where the value is an observable. The goal is to have each object in the array result in the same key with the corresponding value being the outcome of ...

Creating a multiline textarea with ellipsis using ReactJS

Looking to create a component with a multiline textfield that displays ellipsis (...) for text overflow beyond 2 lines. How can I achieve this through CSS only without modifying the actual stored text? Utilizing the React component found at: link Appreci ...

Endless AngularJS loop using ng-view

I recently started experimenting with AngularJS for a new project I am working on, but I have encountered a problem when dealing with routes and views. For the sake of simplicity, I have minimized this example to its basic form, yet the issue persists. Th ...

There are a total of 152 issues found in the index.tsx file within the react

Despite everything working correctly, I am continuously encountering these errors. Is this a common occurrence? What steps can I take to resolve them? I have developed my react application using Javascript instead of Typescript; however, I don't belie ...

What is the best approach for transmitting data to the post method of Node.js using AJAX/jQuery?

A UDP server I have is set up to respond with a different message each time it receives a message. When I hard code the message into the variable "message," everything works fine. However, I want the client to be able to manually type in a message, and t ...

Tips for avoiding multiple reference paths in Angular TypeScript: - Simplify your imports

Setting up Typescript for an Angular 1.5 application has been a bit of a challenge. To ensure that a TS file can be compiled by gulp without any errors, I have to include the following line: ///<reference path="../../../../typings/angularjs/angular.d.t ...

Creating a customizable filter by using the function of an object

I am currently developing a customizable dynamic filter system, similar to the functionalities offered by Yahoo Screener. To achieve this, I have defined an interface for the available filter fields: export interface FilterField { label: string; se ...

Having trouble resolving all parameters for 'Router' in Angular 2 testing with Router

Currently, I am in the process of testing a component that has Router injected in the constructor (TypeScript): constructor( private _router: Router, private dispatcher: Observer<Action>, fb: FormBuilder ) { ... } Here are the test cases ...

Best method for connecting user input with a class

I'm currently working with a WYSIWYG editor (Tinymce) that allows users to post YouTube videos. In order to make the video content responsive, I need to add the class "video-container" around any "iframe" tags inserted when users paste a YouTube link ...

Socket.io continuously refreshing and updating multiple instances

Incorporating socket.io into a small React application, I configured all the listeners within the "componentWillMount" method. See the code snippet below for reference: componentWillMount() { const socket = io(); socket.on('update', f ...

typegrapql encounters an issue with experimentalDecorators

I'm currently delving into TypeGraphQL and working on building a basic resolver. My code snippet is as follows: @Resolver() class HelloReslover { @Query(() => String) async hello(){ return "hello wtold" } } However, ...

Attempting to wipe out a request using ajax to access relationship entities in a ruby on rails framework

I'm currently working on implementing an ajax request to delete a "budget" (known as "orçamento" in Portuguese). These budgets are associated with a "cadastre", where each cadastre can have multiple budgets. Below, you can find the components involve ...

I am experiencing issues with my $ajax request

After running the code snippet below: websiteUrl= "http://192.168.2.171/LoginAuthentication"; $.ajax({ url: 'websiteUrl', type: 'GET', success: function(response) { var title = $(response.responseText).find('a. ...