Problem with Ionic 2 checkboxes in segment controls

I encountered an issue with my screen layout.

https://i.sstatic.net/bFeZN.png

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

Using Angular, Typescript, and ngxs to manage state observables, one may wonder what exactly a variable ending with an exclamation mark (!) signifies. An example of this can be seen in the following code snippet:

Within my TS file, a declaration is present: import { Select } from '@ngxs/store'; @Injectable() export class someService { @Select(someSELECTOR) varName$!: Observable<someType[]>; elements$ = this.varName$.pipe( map(elements => e ...

Tips for saving data from an observable into a variable or property

I've been diligently working on a project utilizing both Angular and Firebase/Firestore. Here is the code snippet that I have implemented: this.cadet = this.cadetCollection.valueChanges().subscribe(x => { this.cadetName = x[0].Cadet; this.cad ...

Get a file transfer from MVC 5 to Angular 2

After gaining experience in C# backend and ASP.Net MVC, I decided to take on the challenge of learning Angular 2. While most of the experience has been positive, I have hit a roadblock with a simple file download task. Despite studying various examples on ...

Create an array variable for services in Angular

My goal is to define this user as an array. users = new BehaviorSubject<any>([]); In my component, I am attempting to add the userID to the array. this.Service.users.push(userID); To subscribe to it, I use the following code: this.Service.users.su ...

Add TypeScript typings for npm utility manually by incorporating type definitions

I'm in the process of incorporating TypeScript into an existing JavaScript project, and I'm currently facing the challenge of adding typings to an npm module that lacks type definitions, which I anticipate will be a common issue. When I try to i ...

Obtain non-numeric parameters from the URL in Angular 2 by subscribing to

How do I handle subscribing to a non-numeric parameter from a URL? Can the local variable inside my lambda function params => {} only be a number? Here's my code: getRecordDetail() { this.sub = this.activatedRoute.params.subscribe( ...

Issue with Angular RC5: Unable to bind to 'myDirective' because it is not recognized as a property of 'div' element

I recently attempted to transition my project to RC5 and utilize NgModules, but I am encountering challenges with references to custom directives. An error is being thrown: "Template parse errors: Can't bind to 'myDirective' since it isn&a ...

Using TypeScript to deserialize various types from a shared object

I am currently dealing with a JSON array containing serialized objects, each of which has a type field. My challenge lies in deserializing them properly due to TypeScript not cooperating as expected: Check out the TypeScript playground for reference. type ...

Storing Passport.js Token Locally: Best Practices

Struggling to save the jwt token provided by passport.js in browser localStorage, I am facing challenges with transferring it from the server to the client as it is generated on the server side. If anyone can assist me with setting the server-generated to ...

Typescript threw an error stating "Cannot access properties of an undefined object" in the React-Redux-axios

As a backend developer, I am not very familiar with frontend development. However, for my solo project, I am attempting to create some frontend functionalities including user login right after setting the password. Below is the code snippet from UserSlice. ...

Tips for eliminating checkboxes from a form

function addCheckbox(){ var labels = document.form1.getElementsByTagName('label'); var lastLabel = labels[labels.length-1]; var newLabel = document.createElement('label'); newLabel.appendChild(Checkbox(labels.length)); ...

React validation functionalities

Incorporating React, I am attempting to implement a validation feature within a footer containing multiple buttons with unique values such as home, orders, payments and more. My goal is to dynamically display an active state for the button corresponding to ...

Managing onChange in a ReactJs project

Currently, my React tsx page features input boxes like the following: <textarea value={this.state.myData!.valueOne} onChange={(e) => this.handleValueOneChange(e)}/> <textarea value={this.state.myData!.valueTwo} onChange={(e) => thi ...

Issue: The Karma plugin in Angular CLI >6.0 is now exported from "@angular-devkit/build-angular" instead

Issue: I'm encountering an error in Angular CLI version 6.0 or higher where the Karma plugin is now exported by "@angular-devkit/build-angular". // Below is the Karma configuration file, you can find more information at // module.exports = function ...

What is the best way to account for the 'elvis operator' within a given expression?

When connecting to my data from Firebase, I noticed that using the elvis operator is essential to avoid encountering undefined errors. Recently, as I delved into creating reactive forms, I encountered an issue with a component I developed that fetches actu ...

I'm having difficulty with the installation of the @angular/CLI package

npm ERROR 404: Package @angular/CLI@latest Not Found ** log: ** 0 info it worked if it ends with ok 1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe', 1 verbose cli 'C:\\Program Files\&b ...

Leveraging Angular for Parsing JSON Data

I have a JSON object that I want to use in my code. The goal is to assign the values of certain properties from the JSON object to four variables in my Angular project. These variables are named as follows: authorText : string; titleText : string; duratio ...

Implementing queuing functionality in Angular's HttpClient

I am facing a similar requirement that was discussed in Add queueing to angulars $http service, but I am looking for an implementation in Angular 4.3 or 5 using the HttpInterceptor from @angular/common/http. The API I am working with has some unique limit ...

Exploring the distinctions between the Decorator and Mediator design patterns when implemented in JavaScript

After delving into JavaScript patterns, I noticed some interesting differences between Angular 4 and Angular 1.x. Angular 4 employs new patterns that caught my attention. What specific patterns does Angular 4 utilize? Is it possible to incorporate the De ...

FInding the inner value of a Vuetify chip

I have a Vue application that utilizes Vuetify chips to display information. I'm trying to log the value inside a specific chip when it is clicked, but I keep getting an undefined error when trying to access the array where the information comes from. ...