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

Error: Ionic 2 encountered an error: Highcharts has produced Error #17 - learn more at www.highcharts.com/errors/17

I'd like to incorporate a highchart gauge in my project, but I'm encountering an issue: Uncaught (in promise): Error: Highcharts error #17: www.highcharts.com/errors/17 error I've been advised to load the highcharts-more.js file, but I&a ...

Solving the issue of localizing the Datetime picker

My date input seems to be saving incorrectly in the database. When I enter a date like 18/02/2020, it gets saved as 17/02/2020 22:00:00. Is this a time zone issue? How can I fix this problem and thank you. Also, if I want to save the date with UTC, how do ...

Executing the Ionic code within the Xcode Swift environment

I have developed an Ionic application that I successfully compiled in Xcode for iOS. Additionally, I have integrated a widget into the application. My goal is to set it up so that when the application is opened using the regular app icon, it displays the m ...

Replacing a component dynamically within another component in Angular 2

I am currently working on integrating a component within another component that has its own view. The component being loaded will be determined dynamically based on specific conditions. Essentially, I am looking to replace one component with another compo ...

Validating a single field name with various DTO types based on conditions in a NestJS application

There is a field named postData in EmailTypeDto, but it has different types based on conditions. It may be confusing to explain in words, but the code makes it clear. export class EmailTypeDto { @IsEnum(EmailType) public type: EmailType; @ValidateIf ...

Choose does not showcase the updated value

My form contains a form control for currency selection Each currency object has the properties {id: string; symbol: string}; Upon initialization, the currency select component loops through an array of currencies; After meeting a specific condition, I need ...

Unable to retrieve iFrame window due to an error

My challenge lies in obtaining the window of an iFrame using this particular code: var frameWindow = document.getElementById("loginframe"); var iWindow = frameWindow.contentWindow; However, I am consistently encountering this error message: Property ...

Is it possible to verify type property names using a union type?

Given type UnionType = 'prop1' | 'prop2' | 'prop3'; type DerivedType = { prop1: string; prop2: number; prop3: boolean; }; Is there a method to define DerivedType in such a way that if I introduce a new member to UnionT ...

Leverage ngrx to streamline action creation for multiple feature modules

My Angular 5 application consists of multiple feature modules, each responsible for assets on specific pages and lazily loaded. src/ |--app/ |--core/ <-- core functionality here |--landing/ |--store/ |--about-us/ Each module has a top-leve ...

Display Angular code and HTML within an Angular webpage without it being rendered

Displaying Angular code and HTML examples on my Angular page is proving to be challenging. No matter what I try, Angular keeps trying to parse it. I attempted using <code>, <pre>, and even this: &lt;div class="name">&#123;&#123; ...

Design: Seeking a layout feature where one cell in a row can be larger than the other cells

To better illustrate my goal, refer to this image: Desired Output <\b> Currently, I'm achieving this: current output Imagine 7 rows of data with two columns each. The issue arises in row 1, column 2 where the control needs to span 5 rows v ...

Troubleshooting Angular2: Issues with ngModel functionality within an ngIf directive

Whenever I attempt to reference an NgModel directive using a template reference variable within an *ngIf statement, I encounter a "Cannot read property 'valid' of undefined" error. Consider the following form as an example: <form (ngSubmit)= ...

What is the best way to limit a property and template literal variable to identical values?

Instead of giving a title, I find it easier to demonstrate what I need: type Foo = "bar" | "baz"; interface Consistency { foo: Foo; fooTemplate: `${Foo} in a template`; } // This should compile (and it does) const valid1: Cons ...

Exploring Angular: Looping through an Array of Objects

How can I extract and display values from a JSON object in a loop without using the keyValue pipe? Specifically, I am trying to access the "student2" data and display the name associated with it. Any suggestions on how to achieve this? Thank you for any h ...

Executing multiple HTTP requests in Angular using the HttpClient

Recently, I came across a concerning issue in my Angular 5 App. It all started with this simple call in my service: interface U{ name:string; } ... constructor(private http : *Http*, private httpC:HttpClient) // Http is deprecated - its a compare test ...

How can I pass Checkbox values to a function in the component in Angular 2?

Hello, I am new to Angular and currently working with NgFor. I have a requirement where I need to display elements that can be selected by the user. Upon selection, I should be able to retrieve the ID in the Component function. However, when I tried usin ...

convert a JSON object into an array field

I am looking to convert a list of objects with the following structure: { "idActivite": 1, "nomActivite": "Accueil des participants autour d’un café viennoiseries", "descriptionActivite": "", "lieuActivite": "", "typeActivite": "", ...

In response to resolving an HTTP header issue with a status of 200 ok during API testing with Postman, what steps can be taken

Hello everyone, I am new to the world of Angular and facing some issues while learning. Following a tutorial on YouTube, I tried to replicate the process with a few modifications. Initially, my get API worked fine when tested with Postman, and the post API ...

Tips for aligning the types of objects transmitted from a Web API backend to a React/Redux frontend

After creating a backend for my app using .net, I now have CRUD operations available to me. When performing a POST action, the response includes an entire new item object: {"Id":"7575c661-a40b-4161-b535-bd332edccc71","Text":"as","CreatedAt":"2018-09-13T15 ...

What could be the reason for my provider loading the data twice?

Recently, I have been following a tutorial on building an Ionic app that displays information about National Parks. The data is stored locally and loaded by a Provider in my application. However, I noticed that the data is being loaded twice by the Provide ...