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

Using Typescript, the type T or a function that returns T can be utilized in various scenarios

You can check out a demonstration on this interactive platform. In creating a simple generic type that represents either a variable or a function returning a variable, there was an issue with the typical typeof arg === 'function' check. The erro ...

Parent observable method encountering an error while grouping multiple HTTP calls in Angular

I am facing an issue with managing multiple http calls and handling errors that may occur during their execution. I want to be able to identify which calls have failed so that I can retry them using a different method. However, without visibility at the co ...

Attempting to create a promise for a dropdown menu in React-Select

I am facing an issue here: type Person = { value: string; label: string; }; Furthermore, I have a promise-containing code block that fetches data from an API and transforms it into the appropriate array type for a React component. My intention is to r ...

Once app.component's ngOnInit is completed, the child's ngOnInit will be triggered in Angular6

I am working on a project where I need to make an API call in the app.component's initialization process. The child component should then wait for the completion of the app.component's ngOnInit() before proceeding. In app.component.ts: ngOnInit ...

I have set up a custom ag-grid three times within a single component, however, only the first instance is properly initialized while the other two instances are not initialized

I have developed a custom ag-grid for reusability in my project. Initially, when I initialize the custom ag-grid in one component, it works perfectly as shown below: example.html <html> <body> <input type="text"> <md-app-aggrid [c ...

Count duplicated values in an array of objects using JavaScript ES6

I am working on creating a filter for my list of products to count all producers and display them as follows: Apple (3) I have managed to eliminate duplicates from the array: ["Apple", "Apple", "Apple"] using this helpful link: Get all non-unique values ...

Having trouble installing the Angular/CLI on macOS Mojave due to a node-pre-gyp error?

I recently formatted my iMac and deleted all files on the hard drive. However, upon installing Angular CLI 7, I encountered an error log message in the terminal console. Environment macOS: Mojave 10.14.2 node: v10.15 npm: 6.4.1 Console Error miguels- ...

Managing clearing values/strings for different input types like text/password upon form submission in Angular2

Here is a code snippet for an HTML form: <div> <form class="form-horizontal" role="form" (ngSubmit)="createUser(Username.value, Password.value)"> <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6"> <input type="text" class=" ...

The scrolling on the image listing webpage is not as fluid as desired

I'm currently working on building a website for displaying images in Angular, similar to Google Photos. The site includes a custom scrollbar that displays the month and year. I want the image list to scroll when the user moves the scrollbar thumb. Her ...

Avoid using the <app-componentName> tag when displaying content in an Angular application

Is there a way to exclude the <app-componentName> tag from being generated in Angular HTML output? Let me illustrate what I mean using an example: Imagine I have a chat-box with a message component structured like this: <div class="chatbox&q ...

Tips for arranging TypeScript AST nodes and generating a TypeScript file as the final result

My objective is to reorganize the code in a way that sorts the link(foo) value based on the string text: import Text from '~/text.js' export default function rule(text: Text) { // Sorting rules alphabetically } Although I have made some progr ...

Displaying data from multiple checkboxes in an Angular application using an array

I'm currently facing an issue with displaying checked data in an Array within my Angular application. Upon clicking the checkbox, I receive a true value, but unfortunately, the data does not display as it contains null values. For reference, here is ...

Declare, condition, and output all in a single statement

Is there a method to condense the content inside the function below into a single line? I want to avoid declaring check. function Example { const check = this.readByUuidCheck(props) if (check) return this.readByUuid(check) } I am seeking ways to ...

What is the process for creating a new type from a nested part of an existing type?

Currently, my website is being developed with a focus on utilizing code generation to ensure type safety when handling GraphQl queries. Certain components within the application receive a portion of an object as a prop. The specific type structure is outli ...

Limit the number of cards displayed per row using Angular Flexbox

I am currently working on a component that is supposed to display a maximum of x cards in each row, with the overflow (x+) scrolling in the horizontal direction. The challenge I am facing is getting exactly x cards to appear in one row, as shown in the ima ...

angular2 Formatting Dates in Material 2 Datepicker

I'm currently utilizing the Angular Material datepicker in my angular4 project. I am looking for a way to format the selected date in the input box with a shorter format such as "May 29, 2017" instead of the current display which is "29/05/2017". Can ...

Is it possible to manipulate an Object within Object typescript?

My recent project involved working with React and Typescript to fetch data from an API. Once the data is fetched, it is saved as an object called coin. However, I encountered a situation where the data may not be fully loaded, resulting in coin being null. ...

Angular - A simple way to conceal a specific row in a mat-table using Angular

I am looking to dynamically hide or show a specific column in a table by clicking on a button. The goal is to hide or delete the weight column when the "hide weight" button is clicked, and then show the weight column when the "show weight" button is clicke ...

I am looking for guidance on removing the bottom line from the ionic 4 segment indicator. Any advice or tips on

.segment-button-indicator { -ms-flex-item-align: end; align-self: flex-end; width: 100%; height: 2px; background-color: var(--indicator-color); opacity: 1; } I am a beginner in hybrid app development and ...

In TypeScript, an interface property necessitates another property to be valid

In the scenario where foo is false, how can I designate keys: a, b, c, bar as having an undefined/null/optional type? Put simply, I require these properties to be classified as mandatory only when foo is true. interface ObjectType { foo: boolean; a: nu ...