Achieving checkbox values in Typescript: A guide

I need help with capturing the values of checked checkboxes and storing them in a string to use in my API. I want to retrieve the value if a checkbox is unchecked.

   <div *ngFor="let x of groupesTable">
       <input type="checkbox"  [(ngModel)]="group" (change)=""> 
       {{x.nom_groupe | uppercase}}
  </div>

I am unsure of the method or approach I should take in TypeScript to achieve this. Any guidance would be greatly appreciated.

This is an updated version

<div class="form-check" *ngFor="let x of groupesTable">
               <label class="form-check-label" for="check1">
               <input type="checkbox" class="form-check-input" nom="check1"  [value]= "x.nom_groupe"
               name="x.nom_groupe" (change)="callMe($event, x.nom_groupe)"  [(ngModel)]="grp">{{x.nom_groupe | uppercase}}
               </label>
</div>

In the .ts file, I have implemented this function:

 callMe(event, nom) {
if (event.target.checked) 
  {
    console.log(nom);
    this.nomgrps=this.nomgrps+nom.toUpperCase()+" ";
    console.log(this.nomgrps); 
  }
  else {
    console.log(this.nomgrps);
  }}

However, it seems like the functionality is not working as expected. Please assist me in troubleshooting why all checkboxes are getting checked when only one is selected.

Answer №1

To ensure consistency, all the checkboxes are checked or unchecked together because they are linked to the same variable: grp. You can either create an array of new form models to manage the checked checkboxes or dynamically add a new property checked within the loop.

For example:

<div *ngFor="let x of groupesTable">
      <input type="checkbox"  [(ngModel)]="x.checked" (change)="foo()"> 
      {{x.nom_groupe | uppercase}}
</div>


foo() {
  let checkedStrings = this.groupesTable.reduce((acc, eachGroup) => {
    if (eachGroup.checked) {
      acc.push(eachGroup.nom_groupe.toUpperCase())
    }
    return acc
  }, []).join(" ")

  console.log(checkedStrings);
}

https://stackblitz.com/edit/angular-dj95pg?file=src%2Fapp%2Fapp.component.ts

Answer №2

When dealing with checkboxes, they can only have two values: true or false. Therefore, you will need an array to store these values. If your groupesTable is an array of objects, you can directly use the object "groupesTable". Otherwise, you will need to store the values in an array.

<div *ngFor="let x of groupesTable">
       <input type="checkbox"  [(ngModel)]="x.checked"> 
       {{x.nom_groupe | uppercase}}
</div>

//or
//declare in your .ts
checkes:boolean[]=[]
//and in your .html
<div *ngFor="let x of groupesTable;let i=index">
      <input type="checkbox"  [(ngModel)]="checkes[i]"> 
       {{x.nom_groupe | uppercase}}
</div>

To retrieve the selected values, you simply need to access the array. Create a function like this:

If your groupesTables is an array of objects, for example

[{id_groupe:0,nom_groupe:'...'},{id_groupe:1,nom_groupe:'...'},..]

Your function could look something like this:

getValuesChecked()
{
  return groupesTable.filter(x=>x.checked).map(x=>x.id_groupe).join(",")  
}
//or 
getValuesChecked()
{
  return groupesTable.filter((x,index)=>this.checkes[index])
       .map(x=>x.id_groupe).join(",")  
}

You can call this function on each change (using ngModelChange), but it's also possible to call it before submitting the data.

Answer №3

Implement ngModelChange Functionality:

HTML Code:

<div *ngFor="let item of groupItems">
   <input type="checkbox"  [(ngModel)]="group" (ngModelChange)="updateSelection(object, $event)"> 
   {{item.group_name | uppercase}}
</div>

Typescript Code:

public selectedItems = [];

updateSelection(object: any, isChecked: boolean){
    if(isChecked) this.selectedItems.push(object);
    else this.selectedItems = removeItem(this.selectedItems, object);

    showSelectedCheckboxes();
}

showSelectedCheckboxes(){
    this.selectedItems.forEach(function(element) {
        console.log(element);
    });
}

removeItem(arr, value) {
    return arr.filter(function(ele){
        return ele != value;
    });
}

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

What is the best way to divide data prior to uploading it?

I am currently working on updating a function that sends data to a server, and I need to modify it so that it can upload the data in chunks. The original implementation of the function is as follows: private async updateDatasource(variableName: strin ...

The solution to enabling Type checking in this scenario is simple: Begin by addressing the issue of "Not assignable," followed by resolving any

After subscribing to an observable projected by a BehaviorSubject from a service, I encountered the following errors when trying to assign the subscribed value to a local variable: error TS2322: Type '{}' is not assignable to type 'DatosAdmi ...

Update to using res.get() instead of res.getHeader()

Looking for assistance with the code snippet below: const compress = require('compression'); export const handleCompression = compress({ filter: function (req: express.Request, res: express.Response) { return (/json|text|javascript|css|fo ...

When using *ngFor with AngularFireList, an error is thrown indicating an invalid

I'm struggling to grasp why I'm getting an invalid pipe argument error with *ngFor when using async. Without async, I'm told that NgFor only supports binding to iterables like Arrays. Oddly enough, the same code works fine on another page bu ...

Tips for setting up the configuration of @typescript-eslint guidelines

I am in the process of transitioning to @typescript-eslint but I am finding the documentation to be quite inadequate. One specific issue I am facing is the errors like the following: Line 58: Expected a semicolon @typescript-eslint/member-del ...

Could you explain the meaning of the :host /deep/ selector?

Can you provide a simple explanation of what the :host /deep/ selector does? :host /deep/ .ui-autocomplete { width: 85%; } ...

Inquiry on SSGHelpers and GetStaticProps functionality with parameterization

I am currently implementing createProxySSGHelpers to prefetch data using trpc in a project I'm developing, but I'm facing an issue where the id from the url params is returning as undefined even though it's visible in the url bar. Below is ...

Encountered an Angular 2 error: NullInjectorError - Http provider not found

I've encountered an issue while trying to access a JSON GitHub service, receiving the error message NullInjectorError: No provider for Http! Although I've attempted to add providers throughout the code, my efforts have been unsuccessful. I' ...

Angular 6 Material now allows for the selection of a mat-tab-link by displaying an underlining bar

My website features a mat-tab-nav-bar navigation bar, but I'm facing an issue with the mat-tab-link blue underlining bar. It doesn't move to highlight the active button, instead, it stays on the first button. However, the buttons do change into t ...

Dependencies of generic types among function arguments

Exploring the implementation of binding in a game engine, I aim to incorporate a touch of typing. /** Engine external functions */ export type Message<TBody> = { } // This function returns the same unique object for the same `s` // An internal engi ...

Guide to setting up react-styleguidist, developing with Create React App, using Typescript, incorporating Material UI, and including

Struggling to configure react-styleguidist (RSG) with Create React App 3 (CRA), Typescript, Material UI, and styled-components. Currently encountering an error: ./node_modules/react-styleguidist/lib/client/rsg-components/ReactExample/ReactExample.js Modul ...

Ways to create a versatile function for generating TypedArrays instances

I'm working on a function that looks like this: export function createTypedArray<T extends TypedArray>( arg : { source : T, arraySize : number } ) : T { if( arg.source instanceof Int32Array ) { return new Int32Array( arg.arraySize ); } ...

Sign up for the observable, retrieve the asynchronous mapped outcome with input from the dialog, and then utilize the outcome from the map

Currently, I am utilizing an API-service that delivers an Observable containing an array of elements. apiMethod(input: Input): Observable<ResultElement[]> Typically, I have been selecting the first element from the array, subscribing to it, and the ...

Exploring code coverage for the sortmethod in Angular applications

Within my project, I have a file named sorting.helper.ts that contains all of my sorting methods: In another file, I then called upon these methods. How can I ensure that both files are included in the code coverage analysis for my .spec file? import { C ...

Redirect all traffic in Node.js/Express to an Angular 2 page

Currently working on a project using Angular 2, Node.js, and Express. Encountering an issue with my routes file when using a wildcard. Whenever I try to access a page other than / (such as /test), it throws the error message: ReferenceError: path is no ...

How to implement automatic clicking using Material Angular components

Looking to incorporate layout tabs from Angular Material into my project: https://material.angular.io/components/tabs/overview Interested in implementing auto-click functionality - how can I instruct Angular to simulate clicking on the "Tab1" link, waiti ...

Encountered an issue while attempting to authenticate CMS signature using pkijs

I am attempting to validate a CMS signature generated with open ssl using the following command: $ openssl cms -sign -signer domain.pem -inkey domain.key -binary -in README.md -outform der -out signature Below is my code utilizing pkijs: import * as pkij ...

Angular2 app hosted on firebase displaying an empty page

After developing an angular2 app, I followed the procedure for Firebase hosting. However, when I try to access my app, it is showing a default page instead. I would appreciate any help or guidance on this issue. ...

Angular 2 Universal Starter Kit - issue with importing 'ProvideRouter'

I am in the process of setting up my project for Angular Universal using the quickstart However, I have encountered several errors while trying to install typings: Benjamins-MBP:vepo Ben$ sudo typings install node express body-parser serve-static express ...

Attempting to eliminate any dates that have already occurred

I am faced with an array containing various dates in string format such as "2016-08-12". My goal is to eliminate any dates that have already passed by comparing them to today's date. I am using TypeScript for this task. Here is a snippet of my datoAr ...