Retrieving the selected checkbox value using Angular 2 TypeScript

I am currently working with Angular 2 Typescript and encountering an issue. I need to submit a form that includes checkboxes, but the problem lies in obtaining the values from the attributes of these checkboxes. Since the checkboxes are dynamic, there can be any number of them present.

 <div class="checkbox" *ngFor="#label of labelList">
      <div class="col-sm-4">
           <label><input type="checkbox" value="{{label.Id}}">{{ label.Name }}</label>
      </div>   
 </div>

Answer №1

My suggestion would be to try the following code snippet (although it has not been tested yet):

<div class="checkbox" *ngFor="let label of labelList">
  <div class="col-sm-4">
    <label>
      <input type="checkbox" value="{{label.Id}}" (change)="checkboxes[$event.target.getAttribute('value')]=$event.target.checked">
        {{ label.Name }}</label>
  </div>   
</div>

You can then save the values of any checkboxes that have been changed in the checkboxes array within your component.

Answer №2

In order to implement checkboxes, I rely on the solution provided by ng2-material checkbox component found here: ng2-material checkbox

Below is an example of how you can incorporate this functionality into your component:

<md-checkbox [checked]="isSelected(label.Id)" (click)="toggleSelection(label.Id)"></md-checkbox>

selectedItems = [];
@Output() selectedItemsChange:EventEmitter<any> = new EventEmitter();

toggleSelection(id) {
  var index = this.selectedItems.indexOf(id);
  if (index === -1) this.selectedItems.push(id);
  else this.selectedItems.splice(index, 1);
  this.selectedItemsChange.emit(this.selectedItems);
}

isSelected(id) {
  return this.selectedItems.indexOf(id) > -1;
}

Answer №3

Provided Input

<input type="checkbox" (change)="handleSelectionChange($event.srcElement, itemData)">

Handling Change Event

handleSelectionChange(checkbox: HTMLInputElement) {
    checkbox.checked === true
      ? performTaskIfTrue()
      : executeActionIfFalse();
}

Answer №4

It is necessary to define the name attribute for a checkbox in order to properly monitor it on the backend system.

Answer №5

enter your code here

submitForm(form:NgForm){
console.log(form.value);
}
<div class="checkbox" *ngFor="#label of labelList">
       <div class="col-sm-4">
            <label><input type="checkbox" name='label{{label.Id}}'  value="{{label.Id}}">{{ label.Name }} </label>
       </div>   
 </div>

Include the label.id within the name attribute so that all values can be retrieved in array form.

Hopefully, this will be beneficial for you.

Answer №6

If you're wondering about how to determine if a checkbox is checked or not, you can easily achieve this by using the ng-model attribute in your input tag.

<md-checkbox ng-model="ctrl.someBooleanValue"></md-checkbox>

For more information, you can refer to angular material md-checkbox and angular material md-checkbox demo

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 proper way to input a value within my object so that it can be passed as a prop in React

Recently, I came across TypeScript and I am eager to incorporate it into my React App before it becomes difficult to do so. However, after spending hours on it, I have encountered a roadblock... I need assistance in figuring out what is going wrong with i ...

Angular Material input field with disabled state and a tooltip

<div> <mat-form-field *> <input matInput #filterBox (keyup)="searchBox(filterBox.value)" disabled /> <mat-label>Filter</mat-label> </mat-form-field> </div> <mat-button-toggle-gro ...

Having trouble installing @angular/cli 4 on Debian?

I'm having trouble installing @angular/cli on my Debian box. I already have the latest versions of Node.js and npm installed. Interestingly, Angular4 works perfectly fine on my Windows machine where I use it daily. However, when I try to get it runnin ...

The functionality of Angular 5 reactive form valueChanges is not functioning correctly

I am currently working with a form inside a service: this.settingsForm = this.formBuilder.group({ names: this.formBuilder.array([]), globalIDs: this.formBuilder.array([]), topics: this.formBuilder.array([]), emails: thi ...

Working with <html> response data in place of Json in Angular 6

My Angular 6 application needed to call a web service that returns HTML data, which I then had to display within a div. Below is an example of the HTML response data from the service: <html> <head> <title>Chart : 180: Abraham, Male, 1 ...

What are the steps for importing KnockOut 4 in TypeScript?

It appears straightforward since the same code functions well in a simple JS file and provides autocompletion for the ko variable's members. Here is the TypeScript code snippet: // both of the following import lines result in: `ko` undefined // impo ...

Angular 4 get request using query strings

The initial code block is performing as anticipated fetchQuotes(): Observable<Quote[]> { return this.http.get(this.url) .map((res: Response) => res.json()) .catch((error: any) => Observable.throw(error.json().error || &apos ...

When using httpService.post, it is expected to pass 2 to 3 parameters, however, 4 were provided. To pass the request object along with FormData

When attempting to upload a file using Angular and web API, I encountered an error indicating that httpService.post expects 2 to 3 parameters but received 4 Here is my Angular code: public UploadSites(fd) : Observable<any> { var url = this. ...

Merging two lists from Firebase using Angularfire 2

I currently have two Firebase List Observables containing data from two different users. Is there a way to merge these two lists into one comprehensive list? Could it be done something like this: this.totalCards = cardsOfUserOne + cardsOfUserTwo; Any he ...

Is there a workaround for using date input type in Safari with Angular?

After doing some research, I discovered that Safari does not support the type="date" attribute. Is there an alternative way to handle dates using jQuery or a datepicker in Angular? Here is my current input: <input [ngModelOptions]="{ standalone: t ...

Is it possible for me to change a selector value?

Currently, I am working on an app that utilizes NGRX. I have a question regarding the store being a readonly place where direct object mutation is not allowed. However, I am unsure about the use of selectors. For example, consider the following NGRX sele ...

Typescript encounters difficulty locating the Express module

My venture into creating my debut NodeJS application has hit a roadblock. Following advice from multiple blogs, I have been attempting to build my first nodejs app in typescript by following the steps below: npm install -g express-generator npm install - ...

What is the best way to retrieve a property from a conditional type using generics?

The code snippet above presents an issue in TypeScript: const exampleFn = function<AttributeName extends 'attributeA' | 'attributeB'>( whatToProcess: AttributeName extends 'attributeA' ? {attributeA: string} : {attri ...

Jest unit tests throwing error "Cannot access property ngModule on undefined" due to issues with SwiperJS integration

I recently integrated Swiper v8 into my Angular v12 project in an Nx monorepo setup. For some background, the Swiper carousel component is declared within a module and exported as one of the libs in the project, identified as @mylib/carousel. Initially, ...

The downloaded zip file appears to be corrupt and cannot be opened

As a newcomer to TypeScript, I embarked on creating a simple function to download a zip file. This is the code I've managed to put together: import fs from 'fs'; import https from 'https'; export function handler(): void { https ...

What is the best way to access the ngClass value in an Angular test?

Here is the content of my component.html file with the ngClass attribute used in the second span element: <span class="container"> <button mat-icon-button [disabled]="disabled" (click)="onButtonClicked()"> <mat-icon>{{ico ...

Constantly receiving an undefined value when trying to access a variable in an ngrx Observable

Here is the code snippet I am working with: language.component.ts form: FormGroup; first: AbstractControl; second: AbstractControl; constructor(private _fb: FormBuilder) { this.first = new FormControl('', [Validators.required, Va ...

Routing issue with TypeScript React and React-Router V4

I've been troubleshooting my code, and although it compiles and runs, it's still not functioning correctly. I'm at a loss as to what I might be doing wrong. Below are snippets of code that I believe are relevant from their respective files. ...

Generate random entries from an object based on specific criteria and append them to a fresh object using Typescript

Experimenting with Ionic2 and Typescript has been my recent focus. I have an object that contains various meals, calorie counts, and meal types (such as vegan). This is how the object looks: [ { "id":14093, "name":"Proteinshake mit Wasser ...

Error: The package name "@angular/compiler" is not valid in Npm

After successfully installing Ionic2 for a new project, I proceeded to set up a continuous integration build. However, running npm install on the build server resulted in failure with the following error: npm ERR! Windows_NT 6.2.9200 npm ERR! argv "C:&bso ...