Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular disable checkbox based on other checkbox value reactive forms

I’m trying to disable the checkbox based on the other checkboxes value.
only one of them can be enabled.

I’m getting this error when enabling one of them, as the subscribed: value is coming in numerously.

ERROR RangeError: Maximum call stack size exceeded
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:191:32)
    at SafeSubscriber.next (Subscriber.js:122:22)
    at Subscriber._next (Subscriber.js:72:26)
    at Subscriber.next (Subscriber.js:49:18)
    at EventEmitter_.next (Subject.js:39:25)
    at EventEmitter_.emit (core.mjs:22784:15)
    at FormControl.disable (forms.mjs:2164:31)
    at Object.next (saxo-browser.component.ts:95:52)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183:16)
    at SafeSubscriber.next (Subscriber.js:122:22)

I’m not sure how to go about this.
this is my code,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

component:

  private initForm(): void {
    this.settingsForm = this.formBuilder.group({
      firstValue:[false],
      secondValue: [false]
    });

    this.settingsForm.get('firstValue').valueChanges.subscribe((value) => {
      if(value === true) {
        this.settingsForm.get('secondValue').disable()
      } else {
        this.settingsForm.get('secondValue').enable();
      }
    });
    
    this.settingsForm.get('secondValue').valueChanges.subscribe((value) => {
      if(value === true) {
        this.settingsForm.get('firstValue').disable()
      } else {
        this.settingsForm.get('firstValue').enable();
      }
    });
  }

html:

    <form name="settingsForm" novalidate [formGroup]="settingsForm">
        <label class="switch">
            <input formControlName="firstValue" type="checkbox" class="form-control">
            <span class="slider round"></span>
        </label>
        <label class="switch">
            <input formControlName="secondValue" type="checkbox" class="form-control">
            <span class="slider round"></span>
        </label>
    </form

>Solution :

It should not trigger the valuechanges with this

enable({emitEvent:false}) // same for disable

And as Alex said, a radio button would be better in this case.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading