Issue with updating boolean values in reactive form controls causing functionality to not work as expected

I am currently facing an issue with validating a group of checkboxes. The main problem is that even though the 'this.dataService.minRequired' variable updates in the service, the validation state does not reflect these changes. I initially thought moving it to the service would solve the problem, but it persisted regardless of whether the variable was in the controller or service.

The checkboxes I am using do not have a 'checked' value or any other way to access their state directly. This limitation has led me to explore various workarounds, and I need to find a solution within these constraints.

card.component.html:

<xyz-checkbox-group orientation="vertical" ngDefaultControl [formControl]="newCardForm.get('eligibility')">
    <div style="float: left; width: 45%;">
        <xyz-checkbox ngDefaultControl [(checked)]="checkedFlag1" id="checkbox1" (change)="checker()">Account is Open and in Good Standing</xyz-checkbox>
        <xyz-checkbox ngDefaultControl [(checked)]="checkedFlag2" id="checkbox2" (change)="checker()">Balance Less Than 30 Days Past Due</xyz-checkbox>
        <xyz-checkbox ngDefaultControl [(checked)]="checkedFlag3" id="checkbox3" (change)="checker()">Annual Income - $200,000.00 (minimum)</xyz-checkbox>
        <xyz-checkbox ngDefaultControl [(checked)]="checkedFlag4" id="checkbox4" (change)="checker()">Current Card Limit - $5,000.00</xyz-checkbox>
        <display-error *ngIf="(submitted && newCardForm.get('eligibility').invalid) || (submitted && newCardForm.get('eligibility').invalid && newCardForm.get('eligibility').dirty)  || (submitted && newCardForm.errors.checks)" 
        error="Only 'Client is a Student' is optional." class="alertLabel"></display-error>

card.component.ts:

  checkedFlag1: boolean;
  checkedFlag2: boolean;
  checkedFlag3: boolean;
  checkedFlag4: boolean;

  ngOnInit() {
    this.forms = new FormArray([
      this.accountDetailsForm = new FormGroup({
        productGroup: new FormControl('', {validators: Validators.required}),
      }), 
      this.newCardForm = new FormGroup({
        address: new FormControl('', {validators: Validators.required}),
        eligibility: new FormControl('', {validators: Validators.required})
      }, this.validateCheckboxes(this.dataService.minRequired)),
    ]);
  }

  public checker(){
    let checked = 0;
    this.checkboxArray = [];
    this.checkboxArray.push(
      this.checkedFlag1, this.checkedFlag2, this.checkedFlag3, this.checkedFlag4
    )

    for(let i  = 0; i < this.checkboxArray.length; i++){
      if(this.checkboxArray[i] == true){
        checked++; 
      }
    }

    if (checked === 4) {
      this.dataService.minRequired = true;
    } else {
      this.dataService.minRequired = false;
    }
  }

  public validateCheckboxes(flag): ValidatorFn{
    return function validate (formGroup: FormGroup){

      console.log("entered with: " + flag)
      if(!flag){
        return {
          checks: true
        };
      }
      return null;
    }
  }

Answer №1

When the function is created, the argument being passed is set and not dependent on your service state. Upon entering the validation function, it is like executing

this.validateCheckboxes(false)

You should create an async function that returns an observable. By turning your minRequired into an observable that emits "true" when conditions are met, you can merge it into the async validator to trigger an error or return true based on the current state.

For more details, refer to the custom validators section in the Angular documentation: https://angular.io/guide/form-validation

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

Angular website showing only app.component.html on the frontend

I'm currently working on developing the frontend for my API and I've encountered an issue while trying to create a new component. Despite my best efforts, including setting up an app-routing.module.ts file, my application only displays the conten ...

What is the best way to access the wrapped input data from an ion-input component in Ionic2?

Is there a way to connect an google.maps.places.Autocomplete to an ion-input in Ionic2? The issue is that in Ionic2, the ion-input wraps the <input> element, making it difficult to access. I attempted to solve this by creating a directive and utiliz ...

Tips on transitioning from Modal1 to Modal2 in Ionic after a successful submit button press?

My survey app requires users to fill out a form and click the Submit Feedback button. Upon successful submission, a message saying "Feedback submitted successfully" should be displayed in Modal2, which is inside another modal named (Modal1). However, being ...

Insert items into an array at a specific index in typescript

Using the map function, I am adding elements to array arr1. Is there a way to specify the starting index position in typescript? For example: If I want to add elements from the 3rd index position of the array, with the first two indices holding a value of ...

"Error TS2339: The property specified does not exist within type definition", located on the input field

When a user clicks a specific button, I need an input field to be focused with its text value selected entirely to allow users to replace the entire value while typing. This is the markup for the input field: <input type="text" id="descriptionField" c ...

The error message displayed in the Typescript Playground is stating that there is no property named 'values' on the type 'ObjectConstructor'

Could someone please take a look at this link? I'm encountering an error with the playground and I'm not sure why. Click here ...

Setting default values for class members in Typescript is important for ensuring consistent behavior and

My model is pretty straightforward: export class Profile extends ServerData { name: string; email: string; age: number; } Whenever I make a server call using Angular 4's $http, I consistently receive this response: { name: string; email: ...

What is the process for defining the default landing page route in Angular routing?

My application currently has only one route, and I want it to start with the URL http://localhost:4200/specialtyQ. However, my application is not loading properly. The code snippet below is what I am using to try to achieve this. How can I correct the URL ...

Troubleshooting: Issues when using jQuery metisMenu in conjunction with *ngIf

We are facing an issue while using the metisMenu with Angular2. There is an *ngIf condition on one of the list items, and its visibility changes based on whether a record is selected. When the li item is shown for additional options, it does not work prope ...

Guidelines for transitioning an AngularJS module for injection into an Angular 2 component

After diving into the Angular 2 upgrade guide and successfully setting up a hybrid app (combining ng1 as a base code with components and services gradually transitioning to ng2), I've hit a snag. How do I incorporate 3rd party ng1 modules so that Angu ...

Experience the quirk of using Angular's mat-button-toggle-group with the multiple attribute, and uncover the

I'm experiencing a strange issue with the mat-button-toggle. Here is the code snippet: <mat-button-toggle-group formControlName="fcCWShowForms" multiple="true"> <mat-button-toggle value="HE" (change)="this.showHe=!this.showHe"> Button ...

Tips for defining a data structure that captures the type of keys and values associated with an object

Is there a way for the compiler to verify the type of value in this scenario? type SomeType = { foo: string[]; bar: number | null; }; type SomeTypeChanges<K extends keyof SomeType = keyof SomeType> = { key: K; value: SomeType[K] }; declare ...

What is the best way to categorize variables?

How can I organize variables together: export let findbyc$: Observable<Object>; export let findbyi$: Observable<Object>; export let findbyo$: Observable<Object>; export let findbyob$: Observable<Object>; I would like to group them ...

Using `useState` within a `while` loop can result in

I'm working on creating a Blackjack game using React. In the game, a bot starts with 2 cards. When the user stands and the bot's card value is less than 17, it should draw an additional card. However, this leads to an infinite loop in my code: ...

Building an advanced numerical input validation system with Angular 7

In AngularJS, the following code is used to create a form with an input field of type "number": <form name="f" novalidate> <input type="number" ng-model="x" name="x"> </form> <div ng-if="f.x.$error.number">NaN</div> Is it p ...

What is the rationale behind an Angular component needing to duplicate an object provided by a service?

As I dive into the HttpClient page within the Angular Fundamentals section, one question that comes to mind is why does the component need to clone the object received from the service handling the HTTP calls? In particular, the code block from the config ...

Creating a layout of <video> components in vue.js, complete with the ability to rearrange and resize them through drag and drop functionality

Despite trying numerous libraries and Vue.js plugins, I have yet to find one that meets all of my requirements. I am in need of creating a grid of video HTML elements that are draggable and resizable with a consistent aspect ratio of 16:9. Additionally, I ...

There was an unexpected error: The development server's address information is not defined

Whenever I attempt to utilize ng serve with SSL and a custom hostname, I encounter the error message "An unhandled exception occurred: Dev-server address info is not defined." Has anyone found a solution to this issue? Here is the command I am using: ng s ...

The Angular CLI release does not match the Angular version

After updating Angular to version 9, my previously smoothly running angular project started throwing this error: This peculiar error message popped up: This version of CLI is only compatible with Angular versions 0.0.0 || ^10.0.0-beta || >=10.0.0 <1 ...

Include Django CSRF token in an Angular 5 form

Currently, I am working on a Django-Angular5 project. I have a login form in Angular and I am facing an issue with adding a CSRF token to the form. Without it, I receive a Forbidden (403) error indicating that the CSRF verification failed due to a missing ...