Problem with Ionic 2 checkboxes in segment controls

I encountered an issue with my screen layout.

The problem arises when I select checkboxes from the first segment (Man Segment) and move to the second segment (Woman Segment) to choose other checkboxes. Upon returning to the first segment, all my previous selections are unchecked even though the form controls still retain the values. I am using a form array where I push a new form control with a value each time a checkbox is checked, and remove it when unchecked.

Here is the code snippet for better clarity:

constructor(public fb : FormBuilder){
   this.checkboxForm = this.fb.group({
        categories : this.fb.array([],CustomValidators.multipleCheckboxRequireAtleastOne)
    });
}


updateCheckedOptions(category, isChecked) {
   const categories = <FormArray>this.checkboxForm.controls['categories'];
   if(isChecked) {
     categories.push(new FormControl(category));
     console.log(categories.controls);
  } 
  else {
     let index = categories.controls.findIndex(x => x.value.id == category.id);
     categories.removeAt(index);
   }

}

And in the view:

 <form [formGroup]="checkboxForm" (ngSubmit)="onSubmit(checkboxForm.value)">
     <ng-template *ngFor="let category of categories; let i=index">
        <ion-checkbox (ionChange)="updateCheckedOptions(category,$event.checked)">
        </ion-checkbox>
     </ng-template>
     <button type="submit" ion-button [disabled]="!checkboxForm.valid">go next</button>
 </form>

Any suggestions on how to solve this issue would be greatly appreciated.

Answer №1

Not sure how you plan to use const categories, but if I were in your shoes, I would approach it like this:

<ng-template *ngFor="let category of categories; let i=index">
     <ion-checkbox [(ngModel)]="category.isChecked">
     </ion-checkbox>
</ng-template>

By selecting or deselecting a checkbox, your data will automatically update. To retrieve the checked checkboxes, simply filter them out:

submitForm(){
   let checkedCategories = this.categories.filter((elm)=>{
      return elm.isChecked;
   })
   console.log(checkedCategories)//Your selected categories here
}

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

Package name "@nx-cloud" is invalid as it does not meet the requirements for Nx 16

Whenever I attempt to install a package in my project, I encounter the following error message: Invalid package name "@nx-cloud" of package "@[email protected]": name can only contain URL-friendly characters. Could this issue be ...

Filtering with case sensitivity customization

I've successfully implemented a custom pipe to filter my data from the database. Here is the code for the pipe: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterPipe implements ...

Updating a null value within the database was done successfully

Currently, I am working with angular CLI version 8.1.0 and have a user list displayed on a mat table. Upon clicking on a specific user, a new page opens up containing two buttons - "approve" and "reject". The issue I am facing is that when I click on "ap ...

Nextjs REACT integration for self-service registration through OKTA

Attempting to integrate the Okta SSR feature for user sign-up in my app has been challenging as I keep encountering this error message: {"errorCode":"E0000060","errorSummary":"Unsupported operation.","errorLink& ...

converting JSON data into an Angular 2 object

I'm encountering a certain problem. The issue lies in a JSON string that contains all the variables from an object. Here's the object: export class UserInfo { ssn: string; userId: string; firstName: string; lastName: string; ...

The Cordova InAppBrowser plugin has not been properly set up

After running cordova plugin list, I noticed that the InAppBrowser plugin is listed. However, when I try to run my code on an android device, I receive this message in the console via Chrome Remote Debugger: Native: InAppBrowser is not installed or you ar ...

How to bring in images from the assets folder using React and Typescript

I'm facing an issue where direct image importing is working, but when using object types, it's not functioning properly. Why could this be happening? I am currently working with "react": "^16.12.0" and "typescript": "~3.7.2" // ./src/assets/baby ...

"Incorporating multiple router modules in Angular 4/5, with a parent router module overseeing all

Is there a way to have multiple router modules in Angular, such as Core and Main with their own separate routing modules, and then import these two routing modules into our parent routing module (app.routing.ts/app.module.ts)? ...

Using TypeScript's generic rest parameters to form a union return type

Right now, in TypeScript you can define dynamic generic parameters. function bind<U extends any[]>(...args: U); However, is it possible for a function to return a union of argument types? For example: function bind<U extends any[]>(...args: ...

Determining when to include @types/packagename in React Native's dev dependencies for a specific package

Just getting started with React Native using typescript. Take the package vector icon for example, we need to include 2 dependencies: 1. "react-native-vector-icons": "^7.1.0" (as a dependency) 2. "@types/react-native-vector-icons": "^6.4.6" (as a dev ...

Using Angular to bind the ngModel to a variable's object property

In my application, I am working with a user object that looks like this: let user = {name: "John", dob:"1995-10-15", metadata: {}} The metadata property of the user object is initially empty. I want to add a new property to the metadata object based on u ...

Unable to make changes to the document

Having trouble updating a document by ID using mongoose and typescript. I'm testing the api and passing the id as a parameter. I've experimented with different methods of updating by ID, but for some reason, it's not working. Can update by ...

NG8003 error: ExportAs 'ngForm' directive not found in the system

I encountered an issue with my first Angular 11 project: No directive found with exportAs 'ngForm'. Despite importing FormsModule and ReactiveFormsModule in app.module.ts, the error persists. Here is the code snippet: This is from product.compon ...

Retrieve information from a URL to transmit to a different page in NextJS using Typescript and AppRouter

I'm struggling with transitioning from the Home page to the Detail page. I've successfully passed data to the URL from the Home screen, but I'm having trouble accessing it in the Detail screen. I'm working with NextJS ver 13, using Type ...

Steps to configure Visual Studio Code to automatically open the original TypeScript file located in the "src" folder when a breakpoint is hit in a Node.js application

I am currently working on a CLI node application and using VSCode to debug it. Everything seems to be working fine, except for one annoyance: when I hit a breakpoint, VSCode opens the source map file instead of the actual TypeScript file located in my "src ...

"I am looking for a way to receive a response from a loopback in Angular7

Currently, I am utilizing angular7 with loopback. While I can successfully retrieve data, I am unsure how to receive error messages and response statuses. It would be helpful for me to understand what my response code is at the time of the request. Output ...

Error caused by properties of a variable derived from an interface in the compiler

I'm confused as to why the compiler is saying that the properties "name" and "surname" don't exist on type "ITest1" within function test1. It's a bit unclear to me: interface ITest1{ name: string; surname: string; age: number; } ...

What could be causing the issue of CSS Styles not being applied to an Angular 2 component with Vaadin elements?

Currently, I am immersed in the tutorial on Vaadin elements using Angular 2 that I stumbled upon here In section 5.3, Styles are applied to the app.component.ts as shown below import { Component } from [email protected]/core'; @Component({ select ...

Steps for releasing a third-party library that is compatible with both Angular 2 and Angular 4

Currently, I am utilizing a third-party library for Angular that is compatible with Angular 2. However, I want to make sure this library can support all versions of Angular, including Angular 4 and Angular 5. How can I go about publishing an updated vers ...

The functionality of router.navigate in Angular 5 seems to be malfunctioning

I am struggling with redirecting a user to another page based on a certain condition. Here is an example of my login component: ngOnInit() { console.log(">>> router", this.router) console.log(">>> activatedRoute", this.activate ...