Working on an Angular project with a reactive form that features a <mat-select>
for selecting cities. Although the dropdown functions properly in displaying and allowing city selection, there's a problem when attempting to submit the form: the selected value for ciudad_id
doesn't seem to be saved or captured correctly in the form object upon submission.
HTML:
<div class="form-group has-default">
<mat-form-field class="input-group full-width">
<mat-icon matPrefix>location_city</mat-icon>
<mat-select matInput placeholder="City" formControlName="ciudad_id">
<mat-option *ngFor="let city of cities" [value]="city.id">{{city.name}}</mat-option>
</mat-select>
<mat-error *ngIf="ciudad_id?.invalid && ciudad_id?.dirty">
The city is required.
</mat-error>
</mat-form-field>
</div>
Within the component, I set up the form and load the cities successfully. However, when the form is submitted, it appears that the value of ciudad_id
is either missing or not accurately captured:
TS:
export class RegisterComponent implements OnInit{
form!: FormGroup;
cities = [];
constructor(private _form_builder: FormBuilder) { }
ngOnInit() {
this.initializeForm();
this.loadCities();
}
private initializeForm() {
this.form = this._form_builder.group({
city_id: ['', Validators.required],
// other form controls...
});
}
loadCities() {
// Cities are loaded from a service and assigned to `cities`
}
onSubmit() {
console.log("Form submitted:", this.form.value);
// Issue persists where `city_id` does not store the selected value
}
}
I have attempted subscribing to value changes using valueChanges
, and verified that the value does change correctly when selecting a different option. Additionally, I've double-checked the form's binding and ruled out any typos or configuration errors. Despite these efforts, the issue remains unresolved.
Has anyone encountered a similar challenge or can shed light on why the chosen value for city_id
isn't retained during form submission?