Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReactiveForms - patchValue and setValue does not work correctly with option emitEvent false #493

Open
blazekv opened this issue Jan 15, 2024 · 3 comments

Comments

@blazekv
Copy link
Contributor

blazekv commented Jan 15, 2024

If ui-switch is part of reactive forms and there is set or patch method used with option emit event false it does not work.

Example code for demo:

demo.component.ts

  constructor(private fb: NonNullableFormBuilder) {
    this.form = this.fb.group({
      test: [false]
    })
    this.form.valueChanges.subscribe((value) => console.log('Changed', value));
  }
  
    test() {
       this.form.patchValue({test: false}, {emitEvent: false})
    }

demo.component.html

    <div [formGroup]="form">
      <ui-switch formControlName="test" checked [ariaLabel]="'checked'"></ui-switch>
    </div>
    <button (click)="test()">change</button>

Expected behaviour:
If button change is clicked there is no output in console (because of emitEvent is set to false)

Actual behaviour:
If button change is clicked there is "Changed" output in console (emitEvent option does not work)

Reason of this strange behaviour is because onChange is called while setting value (in writeValue method), but it was added because some kind of bug - 1382bb1

@jeandat
Copy link

jeandat commented May 16, 2024

Took me a while to find out it came from ui-switch. I confirm, emitEvent is not respected.

@jeandat
Copy link

jeandat commented May 17, 2024

@jeandat
Copy link

jeandat commented May 24, 2024

Indeed in code there is this:

writeValue(obj: any): void {
    if (obj !== this.checked) {
      this.checked = !!obj;
    }

    this.onChangeCallback(this.checked); // <---- HERE
    if (this.cdr) {
      this.cdr.markForCheck();
    }
  }

Why would you want to call the CVA callback when you receive a new value? You should call it only when the internal value has changed after a user action.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants