So I'm working on a reactive form for user details. I have 2 dropdown for province and municipality. After form init, the province field has *ngFor
loop and based on the selection the municipality options will also load using *ngFor
. This is when creating new user but in editing, I have set patchForm
to automatically select/display the existing province and municipality.
In the edit mode of the form, I tried to change the province which causes the municipality to clear the existing value and load the selection. If I don't select a municipality, the form still pass as valid but on the console.log(this.form.value)
I can see that municipality: null
.
html file
<div class="col-sm-12 col-md-3 col-lg-3 col-xl-3">
<div class="form-group">
<label for="province">Province<span class="text-danger">*</span></label>
<select id="province" class="form-control" formControlName="province" (change)="onProvinceSelect()">
<option value="">Please Select...</option>
<option *ngFor="let province of provinces; let i = index" [value]="province">{{ province }}</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-3 col-lg-3 col-xl-3">
<div class="form-group">
<label for="municipality">Municipality<span class="text-danger">*</span></label>
<select id="municipality" class="form-control" formControlName="municipality" (change)="onMunicipalitySelect()">
<option value="">Please Select...</option>
<option *ngFor="let municipality of municipalities" [value]="municipality.name">{{ municipality.name }}</option>
</select>
</div>
</div>
TS file (init form - part)
municipality: new FormControl(null, Validators.required),
province: new FormControl(null, Validators.required)
(if form is on edit)
this.form.patchValue({
province: 'ABC',
municipality: 'DEF'
});
onProvinceSelect() {
// some filtering of municipality based on province
this.form.value.homeMunicipalityCity = null;
}
As of now, I'm adding this line inside the onProvinceSelect()
this.form.patchValue({ homeMunicipalityCity: null });