Deactivate the FormGroup by implementing Validators

In my form, I have a checkbox group named formArray within my checkboxForm. The task at hand is to disable the submit button if none of the checkboxes are checked. To achieve this, I created a custom validator for my checkboxForm and here is my approach:

Ts file

  get formReceivedSummons() {
    return this.checkboxForm.get('receivedSummons') as FormArray;
  }

  ngOnInit() {
    this.checkboxForm = this.formBuilder.group({
      receivedSummons: this.formBuilder.array([])
    });
    this.getReceivedSummons();
  }

  getReceivedSummons() {
    this.receivedSummonsSubscription = this.inquiryStore.summons$
      .subscribe(receivedSummons => {
        this.receivedSummons = receivedSummons;
      });
  }

  addCheckboxes() {
    this.formReceivedSummons.setValue([]);
    this.formReceivedSummons.setValidators([minSelectedCheckboxes(1)]);
    this.receivedSummons.data.items.map(x => {
      this.formReceivedSummons.push(
        this.formBuilder.group({
          itemNo: [x.itemNo],
          isChecked: false,
        }));
    });
  }


function minSelectedCheckboxes(min = 1) {
  const validator: ValidatorFn = (formArray: FormArray) => {
    const totalSelected = formArray.controls
      .map(control => control.value)
      .reduce((prev, next) => (next ? prev + next : prev), 0);

    return totalSelected >= min ? null : { required: true };
  };
  return validator;
}

I included validators in the formArray by using

this.formReceivedSummons.setValidators([minSelectedCheckboxes(1)]);

This is how it was implemented in the html file

    <form [formGroup]="checkboxForm" (ngSubmit)="submitSelectedCheckbox()">
        <ng-container formArrayName="receivedSummons" *ngFor="let summon of formReceivedSummons.controls; let i = index">
            <ng-container [formGroupName]="i">
                <input type="checkbox" formControlName="isChecked"> {{summon.value.itemNo}}
      </ng-container>
    </ng-container>
    <button [disabled]="!checkboxForm .valid">submit</button>
</form>

Although I disabled the button in the checkboxForm, enabling it when one checkbox is selected remains an issue. Seeking guidance on resolving this matter.

Update

Based on research findings from Google and other sources, I made adjustments. Here's what I came up with:

  addCheckboxes() {
    this.formReceivedSummons.setValue([]);
    this.receivedSummons.data.items.map(item => {
      this.formReceivedSummons.push(
        this.formBuilder.group({
          itemNo: [x.itemNo]
          isChecked: [false, Validators.requiredTrue],
        }));
    });
  }

By employing Validators.requiredTrue, the button requires two checkboxes to be selected for activation. However, I aim for the functionality where enabling the button only demands at least one checkbox selection.

Answer №1

Make sure to include the validator for the formarray when initializing the form in the constructor. Following this step, call the addCheckboxes method after receiving the data.

form: FormGroup;
receivedRecords = [];

constructor(private formBuilder: FormBuilder) {
   this.checkboxForm = this.formBuilder.group({
     receivedRecords: new FormArray([], minSelectedCheckboxes(1))
   });

   of(this.someMethodWhichReturnReceivedRecords()).subscribe(receivedRecords => {
      this.receivedRecords = receivedRecords;
      this.addCheckboxes();
   });
}

Within the addCheckboxes method:

private addCheckboxes() {
    this.receivedRecords.map((o, i) => {
      const control = new FormControl(i === 0); // set to true for first item, false for others
      (this.form.controls.receivedRecords as FormArray).push(control);
    });
}

Answer №2

Create a similar function like the one shown below:

Define and export a function as follows:

export function customValidator(form: FormGroup) {
  const formValue = form.value;
  // Implement your validation logic using the formValue.
  if (/* CONDITIONS MET */) {
    return { checkboxesRequired: true };
  } else {
    return null;
  }
}

Set up your form with the custom validator:

this.checkboxForm = this.formBuilder.group({
      receivedSummons: this.formBuilder.array([])
    },  { validator: customValidator });

Remove any validators being added in your addCheckboxes method.

Regardless of adding or removing rows from the receivedSummons FormArray, any changes to the form data in Angular will trigger the customValidator function, passing the current form values for validation purposes.

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

Display HTML tags on an HTML page using TypeScript

In my angular application, I encountered an issue where I needed to call one component inside another component. Initially, I was able to achieve this by simply using the second component's selector in the HTML of the first component: html: <div&g ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Tips for adding temporary text in filter input of Kendo UI Grid using Angular

I'm currently working with Kendo UI Grid in conjunction with Angular, and I am struggling to find a solution for adding text or a placeholder in filter inputs using Typescript. Within my code, I am utilizing the kendoGridFilterCellTemplate: <kend ...

Explore the potential of utilizing Reactive Forms in conjunction with storybook templates

Currently, I am working on developing some custom components and form elements that I intend to include in Storybook. To ensure completeness, I want the stories to utilize FormControl and FormGroup to demonstrate a real-world use case. Here is an example ...

Is it secure to transmit Tenant ID's as GET parameters to the API in a Multi-Tenant database environment?

When working with a Multi-Tenant database, is it secure to pass Tenant ID's as query string parameters to the API while using popular JavaScript-based UI platforms like Angular or Vue and ensuring both the site and the API are HTTPS? For example, let ...

Upon receiving data from the Api, the data cannot be assigned to the appropriate datatype within the Angular Object

I am encountering an issue with the normal input fields on my page: https://i.stack.imgur.com/qigTr.png Whenever I click on the "+" button, it triggers an action which in turn calls a service class with simple JSON data. My intention is to set selectionC ...

Using React Material UI in Typescript to enhance the theme with custom properties

Struggling to customize the default interface of material ui Theme by adding a custom background property to palette. Fortunately, I found the solution thanks to this helpful shared by deewens. declare module '@material-ui/core/styles/createPalette& ...

Issue with the code flow causing nested function calls to not work as expected

I'm experiencing an issue with my code: The problem arises when param.qtamodificata is set to true, causing the code to return "undefined" due to asynchronous calls. However, everything works fine if params.qtamodificata is false. I am seeking a sol ...

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

Tips for retrieving a nested data value within an array

I am currently puzzled by the undefined error I encounter when attempting to access a value using dot notation. The following illustrates my point: My goal is to retrieve the value from within the nested object in the headline color array: ...

Adjust the checked state of the checkbox based on the outcome of the promise's data

Whenever the checkbox is clicked and the resolved data in a promise is false, I want the checkbox to remain unchecked. If the data is true, then the checkbox should be checked. I have set up a codesandbox for this purpose. This example utilizes react and ...

The issue of Angular child components rendering before receiving parent data

My current challenge involves a parent component (app.component) making an http request, storing the result in this.stats and then passing it as a prop to the child component (progression.component). The issue arises when my child component tries to render ...

Adding a checkbox to a div without checking it - checkbox remains untouched

My first jQuery To Do List is almost complete! Each list item has a checkbox that, when checked, moves the item to the Done section. The only issue I'm facing is that the checkbox always remains unchecked. I've tried using .prop() but it doesn&ap ...

Unable to compile Angular 5 using the AOT systemjs configuration

I've hit a roadblock in finding a solution to my issue. Maybe someone out there can lend me a hand. I'm in the process of upgrading from ng 4.4.4 to 5.0.1 and everything seems to be functioning fine in JIT mode. However, when attempting to compi ...

What could be the reason for TypeScript allowing the injection of an invalid type?

I have the following objects and classes that demonstrate dependency injection: abstract class Animal { speak(): void {}; } class Dog implements Animal { speak(): void { console.log('Woof woof'); } } class Cat implements Ani ...

Customizable JSX Attributes for Your TSX/JSX Application

Currently, I am in the process of converting my React project from JavaScript to TypeScript. One challenge I encountered is that TSX React assumes all properties defined in a functional component are mandatory props. // ComponentA.tsx class ComponentA ext ...

Is Typescript generating error TS2411 within its own Typescript module?

After transitioning to using @types in Typescript 2.0, I executed npm i -S typescript @types/typescript to ensure everything was set up correctly with typescript. However, whenever I run tsc on my project and exclude "node_modules", I encounter the same e ...

Issue with Font Requests in Browsers when Using Angular 10 and SCSS with @font-face

I have a project built with Angular 10 that utilizes SCSS for styling. In my _typography.scss file, I have defined some @font-face rules pointing to the font files located in the assets/fonts directory. However, when I run the application, the browser does ...

"Upon receiving a request in Net Core 6 + Angular, null properties are detected in the

Greetings! I am currently working on a project using .NET Core 6 with Angular 12. Within my project, I have a login controller along with its corresponding request model. Interestingly, when I execute the request through Swagger or Postman, everything wo ...

The leaflet popup fails to open for the second time

I used a for loop to create markers on the map. When I click on a marker, a popup opens. However, after clicking on the same marker a second time, the popup does not open. My $scope.resSearchAnnouncement contains JSON data. How can I resolve this issue? ...