How to extract the values from multiple checkboxes in Angular version 10

app.component.html

<form #x="ngForm" (ngSubmit)="submit()">
    <div class="form-check form-check-inline">
            <input [(ngModel)]="details.a" #a="ngModel" type="checkbox" value="1">
            <label class="form-check-label" for="inlineCheckbox1">HELLO A</label>
        </div>
    <div class="form-check form-check-inline">
            <input [(ngModel)]="details.b" #b="ngModel" type="checkbox" value="2">
            <label class="form-check-label" for="inlineCheckbox1">HELLO B</label>
        </div>
    <div class="form-check form-check-inline">
            <input [(ngModel)]="details.c" #c="ngModel" type="checkbox" value="3">
            <label class="form-check-label" for="inlineCheckbox1">HELLO C</label>
        </div>

<button [disabled]="!x.valid" >Submit</button>

</form>

App.Component.ts

export class AppComponent implements OnInit {
details:{
    a:boolean,
    b:boolean,
    c:boolean
} = {
    a:null,
    b:null,
    c:null
}
constructor(){
}
submit(){
    console.log(this.details) //to get true or false if checked
 }  

I am attempting to retrieve the checkbox status and values, intending to store the checked values in variables.

SAMPLE:

If checkboxes 1 and 3 are selected: var x = 1 + 3 x = 4

Answer №1

When you use Object.keys(details), it returns an array containing the keys present in your object, such as ["a", "b", "c"].

Next, we iterate over this array using the map function which is similar to a for loop. The 'i' parameter represents the index and 'x' represents the current item in the array. For example, on the first iteration, x will be equal to "a" (since "a" is the first value in Object.keys(details)). We then check if the value corresponding to the key exists by using if(details[x]), which is equivalent to details["a"]. If the value is true, we add (i+1) to our total.

 let total = 0
    Object.keys(details).map((x,i)=>{
    if(details[x]){
     total = total + (i+1)
    
    }
    
    })

Answer №2

The Element:

export class AppComponent {
  information: Record<'x' | 'y' | 'z', boolean> = {
    x: false,
    y: false,
    z: false
  };

  public get totalNumber(): number {
    const numberMap = { x: 1, y: 2, z: 3 };
    return Object.entries(this.information)
      // filter only the true entries
      .filter(([_key, value]) => value)
      // map the true keys to an array of numbers
      .map(([key]) => numberMap[key])
      // add a default value to prevent reduce error if none selected `[].reduce()`
      .concat(0)
      // calculate the sum of numbers using reduce
      .reduce((prev = 0, curr) => prev + curr)
  }

  submitForm() {
    console.log(this.totalNumber);
  }
}

The Format:

<form #elementForm="ngForm" (ngSubmit)="submitForm()">
    <div class="form-check form-check-inline">
        <input
          id="informationX"
          name="x"
          [(ngModel)]="information.x"
          type="checkbox" />
        <label class="form-check-label" for="informationX">HELLO X</label>
    </div>
    <div class="form-check form-check-inline">
        <input
          id="informationY"
          name="y"
          [(ngModel)]="information.y"
          type="checkbox" />
      <label class="form-check-label" for="informationY">HELLO Y</label>
    </div>
    <div class="form-check form-check-inline">
        <input
          id="informationZ"
          name="z"
          [(ngModel)]="information.z"
          type="checkbox" />
        <label class="form-check-label" for="informationZ">HELLO Z</label>
    </div>

    <button [disabled]="elementForm.invalid" >
    Submit
  </button>
</form>

Check out this example on Stackblitz

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

Retrieve the canvas coordinates for the images starting at lx and ending at rx on the x-axis, and

Currently, I am working on a project where I need to implement a drag and drop feature for an image within a PDF document. The goal is to retrieve the coordinates of the dragged image and use them later for document signing. The situation I am dealing wit ...

Is it possible to prevent casting to any by improving type definitions?

My query can be best elucidated with the following code snippet. The comments within the code aim to provide clarity on the nature of the question. type MediaFormats = "video" | "audio"; type IMediaContent<TType extends MediaFormats, TValue> = { ...

Preventing the upload of empty images in an angular application

When selecting multiple images for upload, I sometimes need to make changes or delete the chosen images before actually uploading them. However, if any of the selected images have a size of 0B, I want to stop the upload process for all images, not just the ...

The challenge of migrating from Angular2 Rc4 to Rc5: dealing with traceur bug

Encountering 'traceur 404' error in console during the migration process of my angular cli project from Rc4 to Rc5 https://i.stack.imgur.com/j4SU1.png Referenced this article for guidance: app.module.ts import {NgModule} from '@angu ...

Is it possible to use Immutable named parameters with defaults in Typescript during compilation?

Here is an example that highlights the question, but unfortunately it does not function as intended: function test({ name = 'Bob', age = 18 }: { readonly name?: string, readonly age?: number }) { // this should result in an error (but doesn&apo ...

Changing a string into a date format with the help of JavaScript AngularJS

My string is as follows: 13-12-2017 05:05 AM I am looking to convert it to the following format: Date 2017-12-13T05:05:00.000Z Attempted Solution: var mydate = '13-12-2017 05:05 AM'; var selectedDate = new Date(mydate); Upon logging the selec ...

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 ...

Proceed with the for loop once the observable has finished

Currently, I have a situation where I am making an http.get call within a for loop. The code is functioning correctly, but the issue lies in the fact that the loop continues to iterate even if the observable is not yet complete. Here is the snippet of my ...

Suggesting prop names for styled-components using TypeScript

Can anyone help me with styled-components to show suggestion props name? I've created a styled component called CardHeader and added props. interface ICardHeader { darkMode?:boolean } https://i.sstatic.net/eDlOv.png https://i.sstatic.net/urxvK.png ...

Trouble viewing Three.js content in Index.html

My current project involves building a website using three.js with typescript. However, I am facing an issue where only the header from my index.html file is displayed when I try to load the website onto a local server. The main problem arises when I atte ...

Is there a way to modify my port to 4900 using npm?

Is there a way to change my port to 4900 using npm, since the command ng s --port 4900 is not working for me? Here is the error message I receive: PS G:\PROJECTS\PetroHSE> ng s --port 4900 ng : The term 'ng' is not recognized as ...

Applying these sorting functions to my specific scenario

Hello everyone, I hope you can help me out with this issue. I have been struggling for hours trying to sort my array of objects in JavaScript based on a specific property, but I just can't seem to get it right. I have referred to some of the top post ...

The error message "Property '$store' is not defined on type 'ComponentPublicInstance' when using Vuex 4 with TypeScript" indicates that the property '$store' is not recognized

I'm currently working on a project that involves using TypeScript and Vue with Vuex. I've encountered an error in VSCode that says: Property '$store' does not exist on type 'ComponentPublicInstance<{}, {}, {}, { errors(): any; } ...

Load an Ionic Toast Controller eagerly

I created a function to monitor the internet connection status. private checkInternetConnection() { this.networkService .isNetworkConnected .pipe(distinctUntilChanged()) .subscribe(connected => { if (connected) { ...

"ng-new" is not currently present in the "@schematics/angular" collection

After removing npm and node, as well as homebrew, I restored them by downloading from the online site. I also installed the Angular cli using npm. Navigating to my desktop in the terminal, I entered: ng new mag-board to initiate my angular project. Howev ...

Having trouble getting automapper-ts registered in the Global Context within an Angular application - Reference to App is Undefined

Ever since the upgrade to Angular 18, it seems like the node package automapper-ts has stopped functioning properly. When attempting to set up Automapper in the global context, the issue arises where app is undefined, resulting in the failure to resolve t ...

Switching Next.js JavaScript code to Typescript

I am currently in the process of transforming my existing JavaScript code to TypeScript for a web application that I'm developing using Next.Js Here is the converted code: 'use client' import React, { useState, ChangeEvent, FormEvent } fro ...

Using arrays as props in React with Typescript

In my code, I have a Navbar component that contains a NavDropdown component. I want to pass an array as a prop to the NavDropdown component in order to display its dropdown items. The array will be structured like this: DropDownItems: [ { ...

Encountering a problem while attempting to host an Angular application on localhost:4200

After executing the ng serve command, I encountered an issue in the browser: An error occurred while trying to resolve "localhost:4200" ("") for "10.238.0.0": rpc error: code = Unknown desc = no such record I apologize if this question seems basic, as I ...

What is the reason behind TypeScript not stating "When comparing a string to a null value, the condition will always return 'false'?"

When comparing a string to a number, an error and warning are generated. But why is there no warning when comparing a string to null/undefined? In this case, the type 'smth' is still narrowed to never without any warning displayed. The strictNul ...