Steps for saving both checked and unchecked checkbox values in Firebase

I have a set of objects that I am using as initial data in my Ionic 3 application:

public interests = [
    { name: 'Travel', checked: false  },
    { name: 'Animals', checked: false  },
    { name: 'Theatre', checked: false  },
    { name: 'Others', checked: false  }
  ];

My goal is to create multiple checkboxes based on this array, and store all the data, including both checked and unchecked items, in Firebase.

Currently, my TypeScript code looks like this:

selectedInterests :any = [];
profileForm: FormGroup;

  constructor(public navCtrl: NavController, 
    public navParams: NavParams, 
    private afAuth: AngularFireAuth, 
    public db: AngularFireDatabase,
    public fb: FormBuilder) {

      this.profileForm = fb.group({
        interests: new FormArray([])
      });
  }

checkItem(data, i, isChecked: boolean) {
    this.selectedInterests = <FormArray>this.profileForm.controls.interests;

    if (isChecked) {
      this.selectedInterests.push(new FormControl({name: data.name, checked: true}));
      console.log(this.selectedInterests.value);
    } else {
      let index = this.selectedInterests.controls.findIndex(x => x.value == data)
      this.selectedInterests.removeAt(index);
      console.log(this.selectedInterests.value);
    }
  }

saveProfile(){
    this.db.object('users/' + this.userId).update({     
      interests:   this.selectedInterests.value        
    }).then(() => {
      console.log("Success!");
      }, error => {
        console.error(error);
      }
    );
  }

And here is my HTML file:

<div formArrayName="interests">
  <ion-item class="interest-list" no-lines *ngFor="let interest of interests; let i = index">
    <ion-label>{{interest.name}}</ion-label>
    <ion-checkbox slot="end" (ionChange)="checkItem(interest, i, $event.checked)"></ion-checkbox>
  </ion-item>
</div>

Currently, only the checked item is showing up in the console:

0: {name: "Animals", checked: true}

But what I actually need is something like this:

0: { name: 'Travel', checked: false  },
1: { name: 'Animals', checked: true  },
2: { name: 'Theatre', checked: false  },
3: { name: 'Others', checked: false  }

How can I achieve this?

Answer №1

To retrieve all the object values in an array, you can directly modify the existing array.

updateCheckedStatus(data, index, isChecked: boolean) {
    let modifiedObj = data;
    modifiedObj.checked = isChecked;
    this.arrayOfObjects[index] = modifiedObj;
    console.log(this.arrayOfObjects);
}

If you only need the objects themselves, you can use the following method.

console.log(...this.arrayOfObjects);

I've included a stackblitz example showcasing your code. https://stackblitz.com/edit/ionic-58mfcp

I hope this explanation proves helpful.

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 JSON node fails to return a value after inserting data through an ajax request

I'm encountering an issue with a jQuery plugin that loads JSON data through an AJAX call and inserts it into an existing object. When I attempt to reference the newly inserted nodes, they show up as 'undefined', despite the data appearing co ...

Unique style pattern for parent links with both nested and non-nested elements

I am in the process of designing a website and I have a specific vision for how I want my links to appear, but I am unsure of how to achieve it. Here is the desired outcome: a red link a green link a red link a green link … Below is the HTM ...

Trouble with Adding and Showing Arrays

function resetValues() { var p = parseFloat($("#IA").val()); var q = parseFloat($("#IB").val()); var m = parseFloat($("#CGCD").val()); var aR = []; aR.push("GCD(" + p + "," + q + ")=" + m); document.getElementById("PGCD").innerHTM ...

Guide to incorporating a scroll-follow effect in multiple directions

I am facing a challenge with managing an array of divs that exceed the dimensions of their container. I have set overflow to hidden on the container and used JQuery Overscroll to achieve an iPhone-like scrolling effect on the map. The problem I'm try ...

JavaScript does not display checkbox values

I am currently testing whether checkbox values appear on the client side. When I execute the code, the alert is not showing anything. I would greatly appreciate any assistance, thank you. <div> <label name="finishing"class=" ...

Is it possible to utilize a JSON file to input events into FullCalendar that can accommodate multiple users?

Here's how I'm integrating event information from my database with FullCalendar using PHP: Retrieve event information from the database. Organize the data into an array and customize formatting, colors, etc. Convert the array to JSON format usi ...

How can the CORS issue be resolved when sending a form from a client to an AWS API gateway function?

Within my front end React application, I am looking to implement a contact form that will submit data to a Lambda function via an API Gateway with a custom domain attached. The frontend operates on the domain dev.example.com:3000, while the API Gateway is ...

Attempting to display a base-64 encoded image in a Next.js application

After following this method, I successfully uploaded my image as a string: const [image, setImage] = useState(""); //------------------^^^^^^^^^^^^^^^^------------------------- const handleImage = (e) => { ...

I'm caught in a never-ending cycle as I navigate through sending information to my Python API and subsequently utilizing that information in the Next.js application to execute the Python script

I am encountering an issue with the response message, getting "Error sending data." The problem seems to arise when trying to retrieve data in server.py that is already specified in the code. For example, instead of using "msg_user", I should use ...

I am interested in utilizing Sequelize, Vue, and Node to implement a query that filters data once it is retrieved to display on my view

Within my project, there's a table tracking user responses to a quiz. By utilizing the following query, I've successfully retrieved all the information from that table and stored it in my TotalQuizResponses array for display: this.totalQuizRespon ...

"Implementing automated default values for Select/dropdown lists in ReactJs, with the added capability to manually revert back to the default selection

After browsing multiple websites, I couldn't find a clear solution on how to both set and select a default value in a select element. Most resources only explain how to set the value, without addressing how to reselect the default value. My Requireme ...

The type 'SVGPathSeg' cannot be assigned to type 'EnterElement' because the property 'ownerDocument' is not present in type 'SVGPathSeg'

I'm attempting to replicate this example using the d3-ng2-service service on Angular 5. Component: OnInit code: let d3 = this.d3; let d3ParentElement: Selection<HTMLElement, any, null, undefined>; let d3Svg: Selection<SVGSVGElement, any, n ...

Issue with Translate3d functionality in fullpage.js not functioning as expected

Currently, I am in the process of constructing a website using fullpage.js with WordPress. Everything is functioning well except for one issue - when attempting to disable the plugin by using destroy() or changing setAutoScrolling to false, the translate3d ...

Add several converted links as variables in each section

The title may not be the clearest, but I am facing a challenge with an ecommerce site that has unmodifiable HTML. My goal is to include additional links for each product displayed on a page showcasing multiple products. Each link should be unique to its re ...

Issue with Jquery UI sortables not functioning properly

Struggling with getting a sortable list to work using jQuery UI. The ul element is receiving the class 'ui-sortable' but nothing seems to be happening. To demonstrate this issue, I created an example since the original javascript code is quite c ...

Babel Compile disrupts the flow of commands

I'm facing an issue while attempting to launch my development server after Babel successfully compiles my files. However, the command chain seems to halt right after Babel displays the compilation success message. Babel has completed compiling 82 f ...

Activate the drop-down menu in Angular 6 by hovering over it with your mouse

I am just beginning my journey with Angular 6 and Bootstrap. Currently, I am working on a Navigation bar that consists of 3 navigation items. One of the nav items is called "Store", and when a user hovers their mouse over it, I want to display a mega menu ...

Occasionally, adding items to an array through pushing may not be successful

Here is a snippet of HTML code: <select name="region-select" id="regions-select" class="form-control"> <option selected=""> </option> <option value="23">Name1</option> <option value="24">Name2</option> ...

Nextjs version 13 encountered hydration failure due to discrepancies between the initial UI and the server-rendered content

I am currently utilizing the latest version 13.1.0. I have implemented a ContextProvider that allows switching between light and dark themes. 'use client'; import { Theme, ThemeContext } from '@store/theme'; import { ReactNode, useState ...

What is causing the return statement to not function properly in the Mongoose findOne method?

I am attempting to locate an item by its name, then update the table and return the updated result. However, the return statement is not working as expected in my code: class addSongsToArtist { constructor(artistName) { Artist.findOne({ ...