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

ES6: Using DataURI to provide input results in undefined output

In my current project, I am facing a challenge. I am attempting to pass image dataURI as an input from a url link to the image. To achieve this task, I know that I have to utilize canvas and convert it from there. However, since this process involves an &a ...

Preventing page reload by using event.preventDefault() does not work with Ajax Form

I've been working on a code snippet to submit a form using Ajax without any page reloads: $( document ).on('submit', '.login_form', function( event ){ event.preventDefault(); var $this = $(this); $.ajax({ data: ...

Animating a div in CSS3 to expand horizontally from left to right without affecting its original position

I am currently in the process of developing a calendar using HTML, CSS, and JavaScript. The main purpose of this calendar is to showcase upcoming and past events. However, I am facing difficulties in ensuring that my event blocks occupy the remaining space ...

To enable the "Select All" functionality in ag-grid's infinite scrolling feature in Angular 4, utilize the header check box

Is there a way to add a checkbox in the header of ag-grid for selecting all options when using an infinite row model? It seems that the headerCheckboxSelection=true feature is not supported in this model. Are there any alternative methods to include a che ...

Error in Next.js PDFtron Webviewer: ReferenceError - 'window' is not defined

Currently, I'm faced with a challenge in setting up a PDF viewer on my nextjs static page. Having recently ventured into Next.js, I'm seeking assistance from you guys to resolve this issue or suggest an alternative approach. While trying to imple ...

Updating content with Ajax in Laravel

Hey, I'm currently facing an issue with my update functionality. Below is the blade code snippet: <div class="form-group floating-label" id="role_colaboration1"> <select name="{{$role}}[]" id="role" class="form-control"> ...

Creating a collapsing drop down menu with CSS

I utilized a code snippet that I found on the following website: Modifications were made to the code as shown below: <div class="col-md-12"> ... </div> However, after rearranging the form tag, the drop-down menu collapse ...

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

Error: HTML code being displayed instead of form value in Ajax request output

For the past couple of days, I've been struggling with an Ajax issue that I just can't seem to figure out. Despite looking for a solution online, nothing seems to work. Below is the code snippet that's causing me trouble: <!DOCTYPE html& ...

What is the best way to execute multiple functions simultaneously in Angular?

Within a form creation component, I have multiple functions that need to be executed simultaneously. Each function corresponds to a dropdown field option such as gender, countries, and interests which are all fetched from the server. Currently, I call th ...

Oops! There seems to be an issue with the code: "TypeError: this

I am just starting out with Angular. Currently, I need to assign a method to my paginator.getRangeLabel (I want to use either a standard label or a suffixed one depending on certain conditions): this.paginator._intl.getRangeLabel = this.getLabel; The cod ...

Easily Update Your Div Content by Simply Clicking a Single Link/Button

I am in need of assistance here. My goal is to display dynamic content within a div. Below you will find the code I currently have: <script type="text/javascript"><!-- function AlterContentInContainer(id, content) { var container = documen ...

Absent observable functions in the RxJS 5.0.0-beta.0 release

I am encountering an issue when trying to use RxJS with Angular 2. The methods recommended from the Typescript definition file are not present on my Observable object... https://i.stack.imgur.com/6qhS4.png https://i.stack.imgur.com/m7OBk.png After inves ...

Exploring ways to efficiently test the nested promises in an Angular service function

Here is a snippet of what my service implementation looks like: TestService.initializeDefaults = function() { var qPromise = $q.defer(); $q.all({ localResource: localResource.fetch(), item: itemResource.fetch() }).then(functio ...

What is the best way to insert an object at a particular position within an array containing numerous nested objects?

This is the given Object: [ { "id": "1709408412689", "name": "WB1", "children": [ { "id": "1709408412690", "n ...

The frontend is not triggering the Patch API call

I am having trouble with my http.patch request not being called to the backend. This issue only occurs when I try calling it from the frontend. Oddly enough, when I tested it in Postman, everything worked perfectly. Testing the backend on its own shows t ...

Azure deployment for Angular app was unsuccessful due to npm startup failure

I've been trying to deploy my Angular application on Azure. While I can successfully publish it using Azure, I keep encountering an error message when trying to access the published site: AggregateException: One or more errors occurred. (One or more ...

Unusual compilation issue encountered in Vue when trying to use a template for a slot

I encountered a strange issue where my Vue compiler was refusing to render the default named slot of a child component. Error: Codegen node is missing for element/if/for node. Apply appropriate transforms first. Even my VSCode highlighted this problem a ...

Which is more effective: using the try-catch pattern or the error-first approach

My main focus is on node.js and express.js, although I am relatively new to JavaScript overall. When it comes to error handling, the official recommendation is to use the try-catch pattern. However, some developers argue in favor of sticking with the tradi ...

Error code 400 encountered during an HTTP POST request - issue stems from incorrect design of views and serializers

I keep encountering the following error: POST http://127.0.0.1:8000/api/creator_signup/ 400 (Bad Request) Every time I try to send data from my AngularJS application to my Django backend. When making a POST request, I used the following code (): fun ...