Tips for extracting IDs from multiple checkboxes that have been selected upon submission in an Ionic 2+/Angular 2+ environment

I am facing an issue with retrieving the ID of the checked item upon submission. While I can successfully fetch the selected ID on change, I am unable to do so on submit. It is worth noting that the data I am receiving does not include a "checked" value. Therefore, there may be a method to insert a selected value into the data structure, but I am unsure how to accomplish this.

HTML

<form [formGroup]="itemForm" (ngSubmit)="submit(itemForm)">
    <ion-list >
      <div>
      <ion-item>
        <ion-checkbox formControlName="selectAll" (click)="checkAll()" [(ngModel)]="selectedAll" ></ion-checkbox>
      </ion-item> 

    <ion-item *ngFor="let item of items">
        <ion-label>
        {{item.text}}
        </ion-label>
        <ion-checkbox [checked]="selectedAll" formControlName="recvd" value="item.id" (ionChange)="select(item)"></ion-checkbox>
    </ion-item>

      </div>
        <button ion-button full type="submit"></button>
    </ion-list>
  </form>

TS

export class MessagesPage {
selectedAll: boolean = false;
 items: [];

constructor(){}

submit(form){

  console.log(form.value, 'FORMVALUE HERE') // this returns true

}

select(item){

  console.log(item) //this returns the selected item on change with the id
}

}

Answer №1

It's interesting that you decided to utilize both formControlName and ngModel in your code. However, it can actually be accomplished using just ngModel as demonstrated below. In order to achieve this, make sure to have a boolean property such as checked within your items array.


    <ion-item *ngFor="let item of items">
        <ion-label>
            {{item.text}}
        </ion-label>
        <ion-checkbox checked="false" [(ngModel)]="item.checked" (ionChange)="select(item)"></ion-checkbox>
    </ion-item>

Answer №2

After exploring different solutions, I managed to come up with my own approach by creating a formbuilder array containing the id's as objects. Utilizing the ion-change value allowed me to easily retrieve the id. Thank you for your valuable input!

SS

this.selectedItemsForm = this.formBuilder.group({
  selectedItems: this.formBuilder.array([])
})

toggleSelection(item: Item, isSelected: boolean){
  const selectedItemsArray = <FormArray>this.selectedItemsForm.controls.selectedItems;

  if(isSelected) {
    selectedItemsArray.push(new FormControl(item));

  } else {
      let index = selectedItemsArray.controls.findIndex(x => x.value.id == item.id);
      selectedItemsArray.removeAt(index);
  }
}

HTML

<form [formGroup]="selectedItemsForm" (ngSubmit)="submit(selectedItemsForm)">
            <ion-list >
              <div>
              <ion-item>
                <ion-checkbox formControlName="selectAll" (click)="checkAll()" [(ngModel)]="selectingAll" ></ion-checkbox>
              </ion-item> 

            <ion-item *ngFor="let item of items">
                <ion-label>
                {{item.name}}
                </ion-label>
                <ion-checkbox [checked]="selectingAll" value="item" (ionChange)="toggleSelection(item, $event.checked)"></ion-checkbox>
            </ion-item>

              </div>
                <button ion-button full type="submit">Submit</button>
            </ion-list>
          </form>

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

Obtaining a string union value dynamically during execution

Question 1: Exploring a component library, material-ui, which offers interfaces and types for customizing the css class values of each component. For the Select component, they define a type as a combination of string literals type SelectClassKey = " ...

Developing Angular 6 for dynamic HTML navigation tabs

Being new to Angular 6, I recently created tabs in HTML and now need to convert them into Angular 6 while also making them dynamic. Here is the original HTML code: <ul class="nav nav-tabs side_nav" role="tablist"> <li role="presentation" class= ...

Tips for incorporating state properties into a component

Currently engrossed in a project revolving around state management for individual components utilizing Angular 7 and NGRX. The challenge at hand is to ensure scalability of the implementation, allowing multiple uses while maintaining independence. Thus fa ...

Ways to obtain the component reference when clicking in Angular 2?

<!--snippet from template file--> <custom-element ... other attributes (click)="handleClick()" </custom-element> @Component({ //selector and templateUrl }) class MainComponent{ handleClick(){ // Obtaining the re ...

Failure to Generate stats.json File When Building Angular 6 with --stats-json Flag

Currently, I am facing an issue with generating the stats.json file for my Angular 6 application. Despite trying a few different methods, the file is simply not being created. It seems that my system specifically requires "npm run" before every Angular CLI ...

Why is it that the resource fails to load in an Angular localhost environment when making an http request?

In the realm of ASP.NET MVC projects lies my creation, a masterpiece utilizing Angular UI components powered by ASP.NET WebAPI. As an explorer navigating the unknown territory of Angular, I present to you the sacred texts residing within my project. Behol ...

Steps for deploying an Angular 2 application without the need for a server

I am embarking on a basic Angular 2 project, however, I do not wish to manage it using npm. Is there any alternative method to initiate the project with the following steps: Compile all *.ts files Transfer compiled js-files to a separate directory (not ...

Is it possible to create Interactive Tabs using a Global BehaviorSubject?

Trying to adjust tab visibility based on different sections of the Ionic app, an approach involving a global boolean BehaviorSubject is being utilized. The encapsulated code has been condensed for brevity. In the provider/service globals.ts file, the foll ...

I am having trouble retrieving child interface data from API using Angular. Can someone help me figure out what I am doing

Recently started with Angular 7 and could use some guidance. I have a JSON stream that appears as follows: { "Id": 25, "Name": "XYZ Corp", "CompanyAddresses": [ { "Id": 39, "CompanyId": 25, "Address1 ...

What are the steps to validate a form control in Angular 13?

My Angular 13 application has a reactive form set up as follows: https://i.sstatic.net/LE219.png I am trying to validate this form using the following approach: https://i.sstatic.net/gxpgN.png However, I encountered the following error messages: https:// ...

What is the process for sharing an Angular-CLI project as an NPM package?

I am developing a custom Angular 2 module using Angular-CLI. What is the process for preparing the module for importing? And, how can I publish the final output to NPM in order to make it accessible for other Angular 2 projects? ...

Steps for accessing a particular item with *ngfor in Angular 2

I'm struggling to figure out why both elements of my array are displaying simultaneously in my browser instead of separately. Take a look at this screenshot to see what I mean: https://i.stack.imgur.com/0EKSn.png Is there a method to specifically ac ...

Issues with compatibility between @ngui/auto-complete and ng2-daterangepicker in Angular 16

Recently, I upgraded my Angular project from version 11 to version 16. Within the project, I am utilizing @ngui/auto-complete and ng2-daterangepicker components. However, I encountered an issue when trying to import NguiAutoCompleteModule and Daterangepick ...

"Silently update the value of an Rxjs Observable without triggering notifications to subscribers

I'm currently working on updating an observable without alerting the subscribers to the next value change. In my project, I am utilizing Angular Reactive Forms and subscribing to the form control's value changes Observable in the following manner ...

The sorting feature is not performing as anticipated

I'm dealing with an array of objects fetched from the backend. When mapping and sorting the data in ascending and descending order upon clicking a button, I encountered some issues with the onSort function. The problem lies in the handling of uppercas ...

Having trouble making API calls in an Angular application

When attempting to call the api using the httpClient method, I encountered an issue where the result was returning as undefined. Below is the code from the services file. contact-service.services.ts import { Injectable } from '@angular/core'; ...

How to Retrieve Superclass Fields in Angular 5 Component

I have a superclass that provides common functionality for components. export class AbstractComponent implements OnInit { public user: User; constructor(public http: HttpClient) { } ngOnInit(): void { this.http.get<User>(& ...

React - Ensure useEffect is triggered only after state update

One of my components (ItemsIndex) is using a custom hook to fetch data from our API. However, the ItemsIndex's useEffect runs first, causing the DOM to not be filled with elements that could be scrolled into view. How can I make sure that the useItems ...

There is an issue with the Svelte TypeScript error related to the $: syntax, specifically stating that a declaration cannot be used in a

I encountered an issue where I am receiving the error message "Cannot use a declaration in a single-statement context" while using $: syntax in a script with lang="ts" within my +page.svelte file. Additionally, when I check the version control system (VCS) ...

Issue encountered: Unable to locate module due to error: Unable to resolve 'crypto' in 'C:UsersmonkeDocumentsEpiconesb-ui ode_modules eflect-metadata'

I am encountering an issue with the reflect-metadata package while working on Angular 13. When attempting to use reflect-metadata, I am getting a strange error message stating "Module not found: Error: Can't resolve 'Crypto' in '*\ ...