I am trying to create an edit form that includes dependent select fields (such as country, state, city). The issue I am facing is that the edit only works when I reselect the first option (car brand) because I am using the event (change) with $event. How can I set a default selected value in the second select field (car model) without having to click on the first select for the event to populate the second select?
Here is my code:
<form #editcarPost="ngForm" (ngSubmit)="updateCar()" [formGroup]="editcarForm">
<div class="form-group">
<label for="carbrand_name">Car Brand</label>
<select class="form-control" id="carbrand_name" formControlName="id_carbrand" (change)="getCarmodel($event)">
<option *ngFor='let carbrand of carbrands' [value]="carbrand.id_carbrand" >{{carbrand.carbrand_name}}</option>
</select>
</div>
<div class="form-group">
<label for="carmodel_name">Car Model</label>
<select class="form-control" id="carmodel_name" formControlName="id_carmodel">
<option *ngFor='let obj of carmodelArr' [value]="obj.id_carmodel">{{obj.carmodel_name}}</option>
</select>
</div>
In my editcar.component.ts file, I have the following setup:
ngOnInit() {
console.log(this.router.snapshot.params.id);
this.dataService.getCars().subscribe(data => this.cars = data);
this.dataService.getCarbrands().subscribe(data => this.carbrands = data);
this.dataService.getEditCar(this.router.snapshot.params.id).subscribe((result)=>{
this.editcarForm = new FormGroup({
id_carbrand: new FormControl(result[0].id_carbrand, Validators.required),
id_carmodel: new FormControl(result[0].id_carmodel, Validators.required),
production_year: new FormControl(result[0].production_year),
plate_number: new FormControl(result[0].plate_number),
vin: new FormControl(result[0].vin),
colour: new FormControl(result[0].colour),
description: new FormControl(result[0].description),
})
})
}
getCarmodel(event)
{
var obj = {
id_carbrand: event.target.value,
}
this.dataService.getCarbrandByID(obj).subscribe(res=>{
this.carmodelArr = res;
})
}
If anyone knows how to set a default value for event.target.value or any other method without needing to click on the first select field, please share your insights!