Angular md-option dropwdown value resets to [0] value after Save() runs

59 Views Asked by At

I have an Angular form that contains md-option dropdowns to fill out details for a project. One of those dropdowns is for a list of cities, which generates based on the State/Region that is selected. When the user clicks Save (Save()) on a newly created project, the page routes to the project/[projectID] page. When it does that, the City dropdown value switches from what the user selected, to the first value in the list. It doesn't do this when the user modifies an existing project and Saves, as the form doesn't need to re-route. Any thoughts on why this is happening?

I'm sure the below isn't nearly enough info; please let me know what else you may need. Many thanks.

project-detail.component.html:

          <!--City Dropdown-->
          <md-select id="cityId" class="mdl-cell mdl-cell--6-col mdl-textfield"
              key="cityId" placeholder="Select city" label="City*"
              formControlName="cityId" error="You must select a city." required (ngModelChange)="onSelectCity($event)">
              <md-option *ngFor="let city of cities" [value]="city.id">
                {{ city.name }}
              </md-option>
          </md-select>

project-detail.component.ts

initForm():

 {

        this.myForm = this.FormBuilder.group({
            .....
            cityId              : [null, [<any>Validators.required, validateDropdown]],
            ......
        });

updateForm():

updateForm() {
        // existing project
        if (!this.newProject) {
....
// Find the project's Country,Region,City,Labortype,AssemblyType in the loaded dropdown values
            let selectedCountry = this.countries.find(country => country.id === this.model.countryId);
            let selectedRegion = this.regions.find(r => r.id === this.model.regionId);
            let selectedCity = this.cities.find(ct => ct.id === this.model.cityId);
            console.log('SelectedCity: ', selectedCity.name);
....
}
}

getCities()

 getCities(regionId: string) {
        return this.locationService.getCities(regionId).then(cities => {
            if (cities && cities.length > 0) {
                this.cities = cities;
                setTimeout(() => { this.myForm.controls['cityId'].setValue(cities[0].id); }, 0);
            }
        });
    }

Save()

 save(model: any, isValid: boolean) {
        console.log('SAVE FUNCTION');
        if (!isValid) {
            console.warn('not valid!');
            return;
        }
        this.submitted = true; // set form submit to true

        // check if model is valid
        // if valid, call API to save project
        console.log(model, isValid);
        let fields = this.myForm.value;
        if (this.newProject) {

            // this.model.name = fields['projectName'];
            this.projectService.createProject(fields).then(
                (newData) => {
                    console.log('New Project Created!', newData);
                    // this.projectService.getLiveProjects();
                    // Open a toast
                    this.mdlSnackbarService.showToast('Project Created');

                    // Reset form fields to show no changes
                    this.myForm.markAsPristine();
                    this.myForm.markAsUntouched();


                    // redirect to Edit Project page for this project
                    // overwrite the route history for the 'new project'
                    this.router.navigate(['/projects', newData.id], { replaceUrl: true });
                    console.log('Navigating to /projects/ProjectID URL')
                }, (error) => {
                    this.mdlDialogService.alert('Failed to create project');
                });
        } else {
            this.projectService.updateProject(fields, this.model.id).then(
                (newData) => {
                    console.log('Project Updated!', newData);
                    // this.projectService.getLiveProjects();
                    // Open a toast
                    this.mdlSnackbarService.showToast('Project Updated!');

                    // Reset form fields to show no changes
                    this.myForm.markAsPristine();
                    this.myForm.markAsUntouched();

                    // redirect to Edit Project page for this project
                    this.router.navigate(['/projects', newData.id]);
                }, (error) => {
                    this.mdlDialogService.alert('Failed to update project');
                });
        }
    }

project.model.ts

// the shared project model class
import { EntityData } from '../../shared/models/entity-data.model';
import { IProjectData } from '@app/interfaces';

export class Project extends EntityData {
    ....
    public countryId: string;
    public countryName?: string | undefined;
    public regionId: string;
    public regionName?: string | undefined;
    public cityId: string;
    public cityName?: string | undefined;
    ....

    constructor(data?: IProjectData) {
        super(data);
        if (data) {
            ....
            this.countryId = data.countryId;
            this.countryName = data.country && data.country.name;
            this.regionId = data.regionId;
            this.regionName = data.region && data.region.name;
            this.cityId = data.cityId;
            this.cityName = data.city && data.city.name;
            ....

        }

    }

}
0

There are 0 best solutions below