The value of a checkbox in Ionic 2

I have implemented the code for reading checkbox values in Ionic 2 following the answer provided. However, I encountered an error message in the console:

 Cannot read property 'indexOf' of undefined

Here is my home.html code:

 <form #leadsForm = "ngForm">
    <ion-item>
        <ion-label>Assign to: </ion-label>
        <ion-select [(ngModel)]="saleRep" name="saleRep">
            <ion-option *ngFor="let agency of agencyReps;let i = index;" value="{{agencyRepsIds[i]}}"> {{ agencyReps[i] }}</ion-option>                        
        </ion-select>
    </ion-item>
    <button ion-button (click)="assignLeads()" block>Assign</button>

    <ion-list >
        <ion-item *ngFor="let t of leads;">
            <h2 [ngClass]="t.status">{{t.fname}} {{t.lname}} | {{ t.status}}</span></h2>
            <label>
                <input type="checkbox" value="{{t}}" [checked]="cbChecked.indexOf('t') >= 0" (change)="updateCheckedOptions(t, $event)" />
            </label>
        </ion-item>
    </ion-list>
</form>

The data for leads in *ngFor is fetched from the backend and displayed correctly.

My home.ts file looks like this:

  export class Leads {
    cbChecked: string[];
    saleRep;

    constructor() { }

    updateCheckedOptions(chBox, event) {
        var cbIdx = this.cbChecked.indexOf(chBox);

        if(event.target.checked) {
          if(cbIdx < 0 ){
               this.cbChecked.push(chBox);
             console.log(chBox);
          }
        } else {
          if(cbIdx >= 0 ){
             this.cbChecked.splice(cbIdx,1);
              console.log(cbIdx);
          }
        }
    }

    assignLeads(){
        console.log('Selected Representative',this.saleRep)
        console.log('CheckBox Value',this.cbChecked);
    }

 }

Thank you.

Answer №1

Here are a couple key points:

  • cbOptions: string[] = []; make sure to assign an initial value to prevent it from being undefined!
  • [checked]="cbOptions.includes(item)"
    remember to use the variable item instead of the string 'item'

Answer №2

The variable cbChecked has not been declared or initialized.

To initialize it, add the following code in your constructor:

 constructor() {
    this.cbChecked=[];
 }

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

Tips for resolving the issue of "The types 'GameState' and 'string' do not intersect, so this condition will always yield 'false'."

I need to display different components based on the value of gameStatus: import React from "react"; import { useAppSelector } from "./hooks/redux"; import EndScreen from "./pages/EndScreen"; import QuestionsPage from "./p ...

Is there a way for me to determine when a user has signed in for the first time?

Issue at Hand I am facing an obstacle in detecting when a user initially connects to Google on my app using Firebase. The method I am currently utilizing is auth.signInWithPopup(googleProvider);. To address this query, I delved into the documentation and ...

What is the best way to activate a click event when I set a radio button to checked?

I am facing an issue with an uninitialized property in my app.component.ts: color!:string; I am trying to automatically initialize the color property when a radio button is selected: <div> <input type="radio" name="colors" ( ...

Can you explain the process of utilizing Angular databinding to display nested information?

I'm facing a challenge with databinding when working with nested arrays in multiple timeslots and windows. Despite understanding the basics, I can't seem to make it work no matter how I try different approaches. It's really frustrating not k ...

Tips for preserving the order of Angular's rearranged list obtained from the backend

Upon opening the page, users encounter a list that can be rearranged using Angular's drag and drop feature. The issue arises when the front-end order differs from the back-end order. What is the most efficient method to maintain the order of this list ...

What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code: Html: <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/> <input type='file' (change)="onSelec ...

Using an Angular variable in a JavaScript function may seem challenging at first, but with

Currently, I have an Angular component that utilizes a JavaScript library (FullCalendar V4). The library triggers a function when certain events occur (such as mouseover or click) and provides an argument that allows me to access the calendar values (start ...

Trouble arises when attempting to generate maps using leaflet.js with data sourced from a local directory

I've been working on an application that requires a map to function offline. I followed a tutorial, which you can find here: To create the necessary files, I generated an mbtiles file of my desired area at this link: The mbtiles file was saved as &a ...

The React-widgets DateTimePicker is malfunctioning and displaying an error stating that it cannot assign to the type of 'Readonly<DateTimePickerProps>'

Hello there! I am a newcomer to TypeScript and I am facing difficulty in understanding an error. Any help regarding this will be greatly appreciated. I have tried searching for solutions online and even attempted changing the version, but I am unsure of wh ...

I am encountering issues with MangoDB Compass connecting to my backend through TypeORM

I am facing a challenge in developing a straightforward web application where I aim to showcase users from a MongoDB database on a React web application. The issue lies with TypeORM and my MongoDB database setup. Unfortunately, my backend repository is una ...

Encounter the error message "Unable to resolve all parameters" after including the Interceptor

Currently, I am in the process of implementing HttpInterceptor functionality. However, upon adding it to @NgModule, I encountered the following error message in Chrome: Uncaught Error: Can't resolve all parameters for JwtInterceptor: (?, ?). at s ...

Component library's Angular 7 Package dependencies

After developing a component library in Angular 7, I encountered an issue when trying to port it to other applications. Even though the Angular library was installed within the component library, it wasn't being bundled with the components for use in ...

Unable to run unit tests on project using my custom React library

If any of you have encountered this issue or know how to solve it, please help me. I created an NPM package that can be found at https://www.npmjs.com/package/@applaudo/react-clapp-ui It installs and runs smoothly in other projects using create react app; ...

Manipulating Angular and Typescript to utilize the method's parameter value as a JavaScript object's value

I am currently working with Ionic, Angular, and Typescript, attempting to dynamically set the value of a location based on the parameter passed from a method. Here is the relevant code snippet: async fileWrite(location) { try { const result = a ...

Manipulate and send back information from Observable in Angular

Here is an example of a scenario where I have created a service to retrieve a list of properties. Within this service, I am utilizing the map function to manipulate the response and then returning the final array as an Observable. My question is: How can ...

Troubleshooting issue with loading local json files in Ionic 3 on Android device

Recently, I've been exploring the process of loading a local JSON data file in my project. I have stored my .json files in the /src/assets/data directory and here is the provider code snippet that I am utilizing: import { Injectable } from '@ang ...

What is the best way to reference class variables and methods within a callback function in Typescript?

While working on my Angular project with the Highcharts API, I encountered a situation where I needed to pass a state code to a class level method after drilling down to a specific map location. Below is the snippet of my current code: ngOnInit() { this. ...

Guide to verifying a value within a JSON object in Ionic 2

Is there a way to check the value of "no_cover" in thumbnail[0] and replace it with asset/sss.jpg in order to display on the listpage? I have attempted to include <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html, but it only shows the thumbna ...

Deleting the previous ion-view from DOM in Ionic v1 with Angular

I have been working on modifying an app built in Ionic v1. Within the app, there is a primary View titled 'Client's Profile' that contains links to two other Views: Support Request and Complaints. In the Support Request view, there is a Te ...

Guide on filtering FlatList Data in react native by selecting multiple categories from an array

User Interface Image I am looking to implement a filter functionality in the FlatList data based on top categories, where the filter button allows for multiple selections. The FlatList data is stored in the HotelData array, and the categories are also re ...