-1

so im trying to create a simple form with 2 select dropdowns.
one select for the countries.
one select for their states.
the idea is to display a list of countries and when one country is selected, the second select gets populated with its main states. ( and obv maintaining data-binding )

I tried to use a simple list of strings for the countries which i succeded to populate the first select dropdown ( although i could not do a placeholder for the select idk why )
after that i declared a second object list with the the cities of each country then do a filter function to filter out only the list of states that are matching the selected country but i could not get to populate the second select dropdown with it. Here is a stackblitz demo which explains better.

Stackblitz

xbl
  • 3
  • 4

1 Answers1

1

You are very close, you just need a proper filter function when the first dropdown has a value selected. Using an event like ngModelChange you can easily get the selected value and execute your filter to find the list of states.

component:

onCountrySelect(selectedCountry) {
    this.filteredStates = this.states.find(item => item.country === selectedCountry).stateList;
  }

html:

<form>
  <select name="countryName" [(ngModel)]="selectedCountry" (ngModelChange)="onCountrySelect($event)">
    <option *ngFor="let c of countries" value="{{ c }}">{{ c }}</option>
  </select>

  <select name="states" id="states" [(ngModel)]="selectedState">
    <option *ngFor="let s of filteredStates" value="{{ s }}">{{ s }}</option>
  </select>
</form>

Stackblitz demo

Nehal
  • 13,130
  • 4
  • 43
  • 59
  • 1
    it's better use find instead of filter :) – Eliseo Nov 16 '22 at 17:20
  • just implemented the solution with filter function and it works like a charm ( i just discovered ngModelChange ) Thank you so much. if u can providea solution with find function if thats possible – xbl Nov 16 '22 at 17:33
  • Answer updated! Thanks everyone for the feedback :) – Nehal Nov 16 '22 at 18:09