Retrieve the status of each p-checkbox upon form submission in Angular PrimeNG

I am dealing with a situation where I have multiple checkboxes in my form next to each field. The checkbox data will not be saved, but I need to determine if all checkboxes are selected before submitting the form. If they are all selected, I want to return true, otherwise false. The challenge is that I have a large number of fields in my form and I need to accomplish this in a dynamic way. Here is a snippet of my HTML code...

                            <div class="ui-g-12 ui-md-12">
                                <div class="ui-g-12 ui-md-11">
                                    <span class="md-inputfield">
                                        <input type="text" pInputText 
                                    formControlName="sequenceOfTotal">
                                        <label>Sequence of Total(27)</label>
                                    </span>
                                </div>
                                <div class="ui-g-12 ui-md-1">
                                    <span class="md-inputfield">
                                        <p-checkbox binary="true">
                                        </p-checkbox>
                                    </span>
                                </div>
                            </div>

Answer №1

If you're looking to make your form dynamic while using formBuilder, consider adding a new formGroup named "checkboxes" within your existing form. This group can store the values of multiple checkboxes with default values set to false and requiring Validators.required.

For instance:

// HTML
<p-checkbox [formControl]="this.form?.controls['checkboxes']?.controls['cb1']"></p-checkbox>
<p-checkbox [formsontrol]="this.form?.controls['checkboxes']?.controls['cb2']"></p-checkbox>
<p-checkbox [formControl]="this.form?.controls['checkboxes']?.controls['cb3']"></p-checkbox>

// TS
this.form = fb.group({
    sequenceOfTotal: [''],
    checkboxes: fb.group({
      cb1: [false, Validators.required],
      cb2: [false, Validators.required],
      cb3: [false, Validators.required],
    }),
});

When you need to ensure that all checkboxes are selected, simply check if

this.form.controls.checkboxes.valid

If you currently use "this.form.value" to send data to the backend, consider creating a separate form for the checkboxes or dividing your formGroup into two.

this.form = fb.group({
    data: fb.group({
      sequenceOfTotal: [''],
    }),
    checkboxes: fb.group({
      cb1: [false, Validators.required],
      cb2: [false, Validators.required],
      cb3: [false, Validators.required],
    }),
});

Remember to update your template and functions accordingly.

Answer №2

@Beerbossa I approached it differently, considering the large number of fields in my form. I utilized an array and assigned each element as false in [(ngModel)] for every checkbox

basicCheckboxes: any[] = [];

setCheckBoxes() {
        for (let i = 0; i < 20; i++) {
            this.basicCheckboxes[i] = false;
        }
}

HTML snippet:

    <div class="ui-g-12 ui-md-12">
         <div class="ui-g-12 ui-md-11">
               <span class="md-inputfield">
                    <input type="text" pInputText formControlName="sequenceOfTotal">
                    <label>Sequence of Total (27)*</label>
                </span>
          </div>
          <div class="ui-g-12 ui-md-1">
                <span class="md-inputfield">
                     <p-checkbox binary="true" [(ngModel)]="basicCheckboxes[17]"  
                           [ngModelOptions]="{standalone: true}">
                      </p-checkbox>
                 </span>
           </div>
   </div>

Lastly, during form submission, I validate if all checkboxes are selected or not

if (this.basicCheckboxes.every(val => val === true)) {
                console.log('All check box selected');
            }

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

I am encountering a PeerInvalid error when attempting to launch myapp on an Android device using Ionic/Angular 4

For the past 3 days, I've been using Ionic and today I decided to try putting my application on my Android devices. However, I've encountered a problem... When I run: ionic cordova run android --device -l -debug I'm getting these errors th ...

React: Dealing with unsuccessful imports

Whenever a device loses internet connection, my app crashes due to an imported component that relies on Google Maps. To address this issue and prevent the app from showing a blank screen, I want to intercept the failed Google Maps import and display an err ...

What is the solution to the strict mode issue in ANGULAR when it comes to declaring a variable without initializing it?

Hi everyone! I'm currently learning Angular and I've encountered an issue when trying to declare a new object type or a simple string variable. An error keeps appearing. this_is_variable:string; recipe : Recipe; The error messages are as follows ...

Error in Typescript index: iterating over properties of a typed object

My scenario involves an interface that extends multiple other interfaces from an external library: interface LabeledProps extends TextProps, ComponentProps { id: string; count: number; ... } In a different section of the codebase, there is an ...

What is the process for managing multiple selections using checkbox code?

I have been following the official tutorial for ag-grid and I've reached a point where I need to manipulate information related to selected checkboxes. However, the documentation lacks detail on how the code actually functions. It might be understanda ...

Guide to embedding a Stripe button within an Angular 2 template

I am encountering an issue while trying to integrate the Stripe button into my Angular 2 app. When I add the code snippet below to my template, Angular removes the script tags. I understand that in Angular 2, script tags are stripped from templates. What ...

Establish an enumeration using universally recognized identifiers

I have a JavaScript function that requires a numerical input, as well as some predefined constants at the top level: var FOO = 1; var BAR = 2; The function should only be called using one of these constants. To ensure type safety in TypeScript, I am att ...

What is the best way to set up my page to detect the "enter" key input when the form is not created with the <form> tag?

Within the HTML code, data is received and stored in variables within my TypeScript file. At the end of the HTML, there is a button that was created separately from any user input containers. This button triggers a function that processes the information i ...

How can I place an icon on a specific location in a Highcharts map?

I am currently utilizing Highcharts to showcase maps within my application. I am aiming to achieve two specific functionalities: 1) Upon clicking on any area, I want that area to be highlighted in red {completed} 2) Upon clicking on any area, I intend f ...

Leveraging TypeScript Generics for Type Reusability

Is there a way to extend the generic types defined in the type T to a function without duplicating code? Can we reuse generics between types and functions? type T<FormType extends 'edit' | 'create' = 'create', RecordType ex ...

The Javascript file is not loading correctly in Firefox, and there is no additional information provided

When attempting to use the import feature in my Typescript code, I encountered an error upon opening it in Firefox: "Loading failed for the module with source flashcard" The import statement in my file is like this import Flashcard from ". ...

The Angular NgForm method form.resetForm does not seem to be resetting properly when dealing with arrays

I encountered an issue with my simple ngForm that was previously functioning well with string input and single select dropdowns. When I added a multi-select dropdown that introduces an array, I started facing a strange problem. Even after using form.formRe ...

How to retrieve a component's property within an Angular2 provider?

As a beginner in OOP, I am currently experimenting with Ionic 2, Angular 2, and TypeScript. In my home.html file, I have an input field connected to the username property in home.ts as shown below: export class HomePage { public username: string; public n ...

Utilize Angular2 to dynamically add new routes based on an array register

Currently, I am utilizing Angular2 for the frontend of my project and I am faced with the task of registering new Routes from an array. Within my application, there is a service that retrieves data from a server. This data is then stored in a variable wit ...

The module '@angular/core' is not found in the Visual Studio Code IDE

It seems like a straightforward code. However, I am encountering the error cannot find module '@angular/core'. course.component.ts import {Component} from '@angular/core' @Component({ selector: 'courses' }) export clas ...

What is the best way to create an optional object parameter in Typescript?

I'm working on a function that looks like this: const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code } Is it possible to make the second parameter (an object) optional? ...

Ensure that the date is valid using Joi without transforming it into UTC format

Is there a method to validate a date using @joi/date without converting it to UTC? I need to ensure the date is valid before storing it in the database. Here's what I've attempted: const Joi = require('joi').extend(require('@joi/ ...

How do you verify an OpenID Connect access token produced by Azure AD v2 in an ASP.NET Core web API?

What is the best way to verify an OpenID Connect Access Token generated by Azure AD (v2) in ASP.NET Core Web API? Here's the situation: I have an Angular 8 Client Application that receives an OpenID Connect access Token post Login. The Client can us ...

Encountering login difficulties during initial login attempts may result in automatic logout upon page refresh within Angular+(Node/express).js framework

After attempting to log in for the first time, I noticed that the authentication process in AuthService sets the loggedInStatus to true. However, in AuthGuard, the loggedIn status is set to false, preventing navigation to the dashboard. Additionally, the c ...

Is it feasible to return data when utilizing the ModalController in Ionic 5, specifically when executing a swipeToClose or backdropDismiss action?

With the latest update to Ionic 5's ModalController, a new feature allows users to swipe down on a modal to close it in addition to using the backdropDismiss parameter. Here is an example of how to enable this functionality: const modal = await this. ...