Populating cascading drop list in Angular/Ionic with previously selected choices

Discussão em 'Angular' iniciado por pr0t0, Abril 4, 2025.

  1. pr0t0

    pr0t0 Guest

    Let's say I have a bunch of locations listed by city name. The locations have elements like country, state, and name. If the user clicks the "add" button, they are presented with a modal to create a new location. That modal has a Country drop list, and a State drop list, the available options of which are filtered based upon the country chosen. This all works fine in my app.

    I'd like to use the same modal for editing a location when the user clicks on a City name in the list of names. This almost works. The complete array and all of the data is passed to the modal. I had to call the onCountryChange() method to get the selectedCountry to populate upon rendering, but the State however, will not.

    In the location-modal.ts:

    @Input() locData: any; //data passed to modal from existing added locations
    countries: any[] = [];
    states: any[] = [];
    selectedCountry: any;
    filteredStates: any[] = [];

    async ngOnInit() {
    //dataService pulls countries and groups from JSON file
    this.dataService.getCountries().subscribe((countryData) => {
    this.countries = countryData.countries;
    });
    this.dataService.getStates().subscribe((stateData) => {
    this.states = stateData.states;
    });
    if(this.locData.country) {
    //if I do not call this in onInit, a location to be edited does not display the country
    this.onCountryChange(this.locData.country);
    }
    }

    onCountryChange(cntry: string) {
    this.selectedCountry = cntry;
    this.locData.category = this.selectedCountry;
    this.filteredStates = this.states[this.selectedCountry] || [];
    }


    And the location-modal.html looks like this:

    <ion-item>
    <ion-label position="floating">Country</ion-label>
    <ion-select [(ngModel)]="selectedCountry" (ionChange)="onCountryChange(selectedCountry)" okText="Choose Country" cancelText="Cancel Choice">
    <ion-select-option *ngFor="let Country of countries">{{ Country }}</ion-select-option>
    </ion-select>
    </ion-item>
    <ion-item>
    <ion-label position="floating">State</ion-label>
    <ion-select [(ngModel)]="locData.state" okText="Choose State" cancelText="Cancel Choice">
    <ion-select-option *ngFor="let state of filteredStates">{{ state }}</ion-select-option>
    </ion-select>
    </ion-item>


    Is this possible? I assume my approach is incorrect. I've tried various change detection efforts, but they did not work, or more accurately, I did not do them properly.

    Any help would be greatly appreciated, thank you!

    Continue reading...

Compartilhe esta Página