Check at least one checkbox in Ionic 3

My Ionic 3 form consists of 3 checkboxes fields:

<form [formGroup]="bookingForm" (ngSubmit)="addBooking()">
<ion-card>
  <ion-card-content>
    <ion-item-group formGroupName="period">
      <ion-list>
        <ion-list-header>
          Select the Period:
        </ion-list-header>
        <ion-item>
          <ion-label>Morning</ion-label>
          <ion-checkbox formControlName="morning"></ion-checkbox>
        </ion-item>
        <ion-item>
          <ion-label>Afternoon</ion-label>
          <ion-checkbox formControlName="afternoon"></ion-checkbox>
        </ion-item>
        <ion-item>
          <ion-label>Night</ion-label>
          <ion-checkbox formControlName="night"></ion-checkbox>
        </ion-item>
      </ion-list>
    </ion-item-group>
  </ion-card-content>
</ion-card>
<button ion-button color="primary" block type="submit" [disabled]="!bookingForm.valid">Add</button>

I aim to ensure that at least one checkbox is selected by the user.

This snippet from my TS file includes the form builder code:

  constructor(
    private formBuilder: FormBuilder
  ) {
    this.bookingForm = this.formBuilder.group({
      //... other fields in the form ...
      period: this.formBuilder.group(
        {
          morning: false,
          afternoon: false,
          night: false
        },
        Validators.requiredTrue
      )
    });
  }

The validator isn't functioning as intended. The Add button remains enabled by default, allowing users to submit the form without selecting any checkbox.

Answer №1

To ensure data integrity, it is essential to implement a group validator:

  constructor(
    private formBuilder: FormBuilder
  ) {
    this.bookingForm = this.formBuilder.group({
      //... other fields in the form ...
      period: this.formBuilder.group(
        {
          morning: false,
          afternoon: false,
          night: false
        },
        { 
           validator: (c: AbstractControl)=> {
           if (!c.get('morning').value &&
               !c.get('afternoon').value && 
               !c.get('evening').value)
               return { pickone: true};
          return null;
          }
       })
    });
  }

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

The Angular component seems to be failing to refresh the user interface despite changes in value

Recently, I created a simple component that utilizes a variable to manage its state. The goal is to have the UI display different content based on changes in this variable. To test this functionality, I implemented the component and used a wait function to ...

Ways to retrieve and upload a blob from a file object

After receiving a file object via an HTML input on-change event in my component.html: onFileSelected(event) { this.selectedFile = event.target.files[0]; } Now, I need to send a POST request to upload the image to the database. The database only acc ...

How to retrieve information from JSON files utilizing arrays

I have a JSON object that contains connection points data in an array. Here is an example of the structure: assetType : "this" connectionPoints:Array(1) type:{name: "Structure", In my TypeScript file, I am handling this data like so (entity represents ...

Learn how to dynamically disable a button based on the input state matching an email pattern!

I'm facing an issue with my login form that has 2 input fields and a login button. One of the input fields requires a valid email pattern. If any of the input fields are left empty, the login button becomes disabled. However, when an incorrect email p ...

Is it possible for a button to be assigned to a variable upon creation, but encounter an error when trying to

const button:Element = document.createElement("button");//This works fine const button:HTMLButtonElement = document.createElement("button");//This works too const button2:Element = document.getElementsByTagName("button");//Why does this give an error? con ...

Vue cannot detect the component that is provided by my plugin

This unique plugin, currently only includes a single component (coded in TypeScript): import _Vue, { PluginObject } from "Vue"; import MyComponent from "./MyComponent.vue"; const VuePlugin: PluginObject<void> = { install(Vue: typeof _Vue): void { ...

Creating a ref in React with TypeScript to access the state of a child component

Is there a way to access the state of a child component within the parent component without using handlers in the child or lifting the state up in the parent? How can I utilize refs in React with TypeScript to createRef and retrieve the child's state ...

Unable to assign a value to an undefined property in TypeScript

I need to store data in an object and then add it to another object let globalSamples = {} as any; let sample = { } as ISamplesDetail []; sample = []; for (let i = 0 ; i<this.prelevementLingette.samplesDetail.length; i++) { sample [i].id= thi ...

Utilize angular animations for enhancing the interactivity of a component

My Angular 6 page has three different angular components that I want to animate based on a certain condition: <component1 [@componentState]="componentToShow === 0 ? 'active' : 'inactive'"></component1> <component2 [@comp ...

Library of Functions in Angular 2

As I develop my application, I'm considering creating a functions library that can be utilized by various components. What would be the most effective approach to achieve this? Should I create a service containing all the functions, or rely on classes ...

The best approach for setting a select value and managing state in React using TypeScript

Currently, I am in the process of familiarizing myself with TypeScript within my React projects. I have defined a type for the expected data structure (consisting of name and url). type PokedexType = { name: string; url: string; } The API respon ...

`What is the best way to transfer an observable to a child component?`

I am facing an issue with passing an Observable down to a child component. I have tried various solutions but none seem to work. parent.component.ts: export class ParentComponent { items$ = of([{name: "Item 1"}, {name: "Item 2"}]); } ...

Connecting conversations in react

When working with jQuery, I often utilize the modal dialog chaining technique. For example: $.Deferred().resolve().promise() .then(function () { return runDialog1(someProps); // return promise }) .then(function (runDialog1Result) ...

Is it possible to retrieve the signature for every method within a class?

Let's consider a scenario where we have a class defined as follows: class Actions { static FooAction = 'foo' as const; someAction1() { return { type: Actions.FooAction, payload: {a: 1, b:2} }} static BarAction = &apos ...

Challenges arise when working with multiple promises while attempting to retrieve download URLs from Cloud Storage

My goal is to save each downloadURL from multiple promises (files being uploaded) in an array while iterating through them. However, what's happening is that I only get the first output for every item, regardless of how many items I upload. It keeps g ...

Expanding function parameter types using intersection type in Typescript

As I delve into the world of intersection types to enhance a function with an incomplete definition, I encountered an interesting scenario. Take a look at this code snippet: WebApp.connectHandlers.use("/route", (req:IncomingMessage, res:ServerResponse)=& ...

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...

Issue encountered in Angular installation of Jest: unable to read property 'matches' as it is undefined

Need help with using jset in my angular project. When attempting to install with the command: npm install jest --save-dev An error is encountered: npm ERR! Cannot read property 'matches' of undefined Important to note that before installing j ...

Sending JSON Object using NavController

I am trying to send a JSON Object to another Page in my Ionic 2 application. However, when I attempt to do so, I encounter the error: Cannot read property 'user' of undefined. While researching for a solution, I came across a similar question ...

Troubleshooting: Socket.io integration in Angular is not functioning within a .then() statement

Upon running this code snippet in a component: const videoholder = <HTMLDivElement>( document.querySelector('#videoholder') ); const myPeer = new Peer(this.userid, { host: '/', ...