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.
CodePudding user response:
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>