Search code examples
angulartypescriptangular-reactive-formsng-zorro-antd

nz-switch is not working correctly due to update with value


<form [formGroup]="businessFoodHygieneForm">
  <div class="box p-4 d-flex jc-between ai-center">
     <span>
        Food Hygiene Link
     </span>
     <label>
      <nz-switch
      class="switch-middle ms-2"
      formControlName="foodHygieneLink"
      (ngModelChange)="onFoodHygieneChange($event)">
      </nz-switch>
  </label>
 </div>
</form>

ts component:

foodHygieneLink: new FormControl(''),

this.businessFoodHygieneForm.patchValue({
  foodHygieneLink:
    selectedBusiness?.foodHygieneLink,
});

onFoodHygieneChange(status: boolean): void {
    this.foodHygieneLink = status;

    const body = { foodHygieneLink: status ? 'Yes' : 'No' };

    this.bizStore.dispatch(
       businessAction.updateBusiness({
          body: body,
          bid: this.bid,
       })
     );
   }

I try to update using nz-switch and updated successfully but the switch button is not working if the switch is updated with "No". It should be off but always on.


Solution

  • What I suspect is that possibly your foodHygieneLink value from the observable is either 'Yes' or 'No' instead of the boolean value.

    Thus the <nz-switch> will be set to open when the value is No.

    You can solve it by converting the 'Yes' or 'No' to a boolean value before setting the value to the foodHygieneLink FormControl.

    this.businessFoodHygieneForm.patchValue({
      foodHygieneLink:
        selectedBusiness?.foodHygieneLink === 'Yes',
    });
    

    Demo @ StackBlitz