How to dynamically disable a checkbox in Angular reactive forms depending on the value of another checkbox

I am attempting to deactivate the checkbox based on the value of other checkboxes. Only one of them can be activated at a time.

When trying to activate one of the checkboxes, I encounter an issue where the subscribed value is being repeated multiple times.

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 am uncertain about how to resolve this issue. Below is my code,

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>

Answer №1

Don't expect the value changes to occur using this method

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

Furthermore, Alex suggested that a radio button might be more suitable in this scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting multiple values on a form can be accomplished by using the appropriate form fields

When it comes to setting values on fields, I am aware that I can choose between using setValue or patchValue However, I am currently encountering a situation where I need to avoid setting the value on each field individually. Take a look at my f ...

Using Angular 2 to assign unique ids to checkbox values

Is there a way to retrieve the value of a checkbox in Angular 2 without needing an additional Boolean variable? I am trying to toggle the enabled/disabled state of an input field based on the selection of a checkbox. While I know this can be accomplished ...

What is the best way to convert a date to ISO 8601 format using JavaScript? Are there any built-in functions or methods in

Currently, I am using this function to set the duration: const setDuration = () => { const currentDate = new Date(); const newDate = new Date(currentDate.getTime()); const year = newDate.getUTCFullYear(); const m ...

The AppModule's CanLoad protector

I recently developed an Angular application using angular-cli and successfully implemented CanLoad guard for my modules. The CanLoad check verifies if the user is logged in before loading a module. My question is, can I apply CanLoad guard to AppModule as ...

Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table? I have successfully implemented my selection functionality, where I am able to mark a planet as "selecte ...

Adjusting the value of a mat-option depending on a condition in *ngIf

When working with my mat-option, I have two different sets of values to choose from: tempTime: TempOptions[] = [ { value: 100, viewValue: '100 points' }, { value: 200, viewValue: '200 points' } ]; tempTimesHighNumber: TempOpt ...

What is the process of changing a number to the double data type in JavaScript or TypeScript?

Within a single input field, users can enter various numbers such as 12, 12.1, 12.30, and 12.34. The challenge is to pass this value in a service call where only the value can be sent as a number but with two decimal points. let a = input //a will be a ty ...

The system couldn't locate the module: Issue: Unable to find module 'fs' within the directory

I am currently working on integrating the ADAL JS sample code from this link into a SharePoint framework client web part. My code is fairly straightforward, as I have already installed packages like adal, fs, and node-fs using NPM. However, when running t ...

Error: DecimalProvider is not provided by the injector

Encountering the following error message: NullInjectorError: R3InjectorError(StudentModule)[DecimalProvider -> DecimalProvider -> DecimalProvider -> DecimalProvider]: https://i.stack.imgur.com/e8D6o.png Despite importing the DecimalPipe into the ...

Utilizing TypeScript with React to dynamically select which component to render

My task seemed simple at first: to render a React component based on its name/type. Here is an example of how it is used: // WidgetsContainer.ts // components have a difference in props shape! const componentsData = [ { type: 'WIDGET_1', ...

If the input is unmounted in react-hook-form, the values from the first form may disappear

My form is divided into two parts: the first part collects firstName, lastName, and profilePhoto, while the second part collects email, password, confirmPassword, etc. However, when the user fills out the first part of the form and clicks "next", the val ...

Tips for verifying internet connectivity and accessing stored data in localstorage

I'm working on my home.ts file and I need to use localStorage items when the internet connection is offline. However, I am encountering numerous errors when trying to add an IF condition in my code. Specifically, I want to access the getItem method be ...

Troubleshooting a Missing Angular (8) Pipe Error in Your Ionic 4 Application

Despite seeing similar questions posted here, none have provided a solution to my issue. I believe I am implementing it correctly, but clearly something is not right. In the app I'm developing with Ionic 4, I need to add a key to a URL in a gallery. ...

Determine if lazy loading is functioning properly through programming

When it comes to Angular, ensuring lazy-loading remains intact can be tricky. Simply importing something from a lazy-loaded module into the app module can result in eager loading. That's why I make it a point to check for such errors during PR reviews ...

Click to Rotate Angular Chevron

Is it possible to animate the rotation of a chevron icon from left-facing to right-facing using Angular? CSS: .rotate-chevron { transition: .1s linear; } HTML: <button [class.button-open]="!slideOpen" [class.button-close]="slideOpe ...

Tips for including an authorization token in an HTTP request

I encountered a 401 unauthorized error when trying to access my REST endpoint, likely due to the security measures I have implemented. I suspect that there might be an issue with how I am handling the HTTP headers. The application utilizes a Spring Boot b ...

The build error TS1036 is thrown when a function with a return statement is moved to index.d.ts, even though it worked perfectly in a standard TS file

In my project using Node v14.x and StencilJS (React) v2.3.x, I encountered an issue with a test-helper file containing a function that converts string-arrays to number-arrays: export function parseNumericStringOrStringArrayToIntegers(value: string | (strin ...

Troubleshooting a Docker EPERM issue while attempting to compile an Angular application within a container

Our team is currently in the process of containerizing our existing stack using Docker and Docker Compose. This is a simplified version of our Docker Compose file with the relevant services: version: '3.8' services: #FO angularproject: c ...

Determine the date and time based on the number of days passed

Hey there! I have a dataset structured like this: let events = { "KOTH Airship": ["EVERY 19:00"], "KOTH Castle": ["EVERY 20:00"], Totem: ["EVERY 17:00", "EVERY 23:00"], Jum ...

Associating function parameters with object types in TypeScript

In the conclusion of this post, I provide operational code for associating object types with a function that accepts an object containing matching properties. The code snippet I shared results in 'result' being resolved as: type result = { GE ...