0

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 });

Rye
  • 445
  • 4
  • 15

1 Answers1

0

you can solve using pipe async and two observables.

1.-Declare two observables

  province$ = this.service.getProvince();
  municipy$;

2.-Create a function to create the form

createForm(data: any) {
    data = data || { province: null, municipy: null };
    return new FormGroup({
      province: new FormControl(data.province),
      municipy: new FormControl(data.municipy)
    });
  }

3.-Create a function that return an Observable of municipies

  listenChanges(form:FormGroup) {
    return form.get("province").valueChanges.pipe(
      distinctUntilChanged(),
      startWith(form.value?form.value.province:null),
      switchMap(res => this.service.getMunicipy(res)),
      tap((res: any[]) => {

        if (!res || !res.find(x => x == form.value.municipy))
          form.get("municipy").setValue(null);
      })
    );
  }

4.- when create the form use the function listenChanges

this.form = this.createForm({ province: "b", municipy: "bb" });
this.municipy$=this.listenChanges(this.form)

The .html

<form *ngIf="form" [formGroup]="form">
  Province:
  <select formControlName="province">
    <option *ngFor="let prov of province$|async" [ngValue]="prov">{{prov}}</option>
  </select>
  Municipy:
  <select formControlName="municipy">
    <option *ngFor="let prov of municipy$|async" [ngValue]="prov">{{prov}}</option>
  </select>
  </form>
  <button (click)="changeValues()">Change</button>

The stackblitz

Update BONUS:how put a "loading.."(*)

If we defined too Subject

  loading$=new Subject<boolean>()
  loadingDebounce$=this.loading$.pipe(debounceTime(50))

We can use this.loading$.next(true) and this.loading$.next(false) in the "listenChanges" function using "tap"

  listenChanges(form:FormGroup) {
    let alive=true;
    return form.get("province").valueChanges.pipe(
      distinctUntilChanged(),
      startWith(form.value?form.value.province:null),
      tap(()=>this.loading$.next(true)),
      switchMap(res => this.service.getMunicipy(res)),
      tap((res: any[]) => {
        this.loading$.next(false)
        if (!res || !res.find(x => x == form.value.municipy))
          form.get("municipy").setValue(null);
      })
    );
  }

And our form like

<form *ngIf="form" [formGroup]="form">
   Province:
   <select  *ngIf="{data:province$|async} as provinces" formControlName="province">
      <ng-container *ngIf="provinces.data">
        <option [ngValue]="null" hidden>Select one</option>
        <option *ngFor="let prov of provinces.data" [ngValue]="prov">
          {{prov}}
        </option>
      </ng-container>
      <option *ngIf="!provinces.data">Loading....</option>
   </select>
   Municipy:
   <ng-container *ngIf="{data:municipy$|async} as municipies">
      <ng-container *ngIf="{obs:loadingDebounce$ | async} as loading">
         <select formControlName="municipy">
            <ng-container *ngIf="!loading.obs">
              <option [ngValue]="null" hidden>Select one</option>
              <option *ngFor="let prov of municipies.data" [ngValue]="prov">
                {{prov}}
              </option>
            </ng-container>
            <option *ngIf="loading.obs">Loading....</option>
         </select>
      </ng-container>
    </ng-container>
</form>

(*) well, a brief explain this "extrange" *ngIf="{data:municipy|async}". This is well explained in this Yury Katkov's entry blog. An if of this kind always return true, becouse is an object, sometimes get the value {data:null} and sometimes {data:[.....]} so the elements under the <ng-container> is showed allways

Eliseo
  • 50,109
  • 4
  • 29
  • 67