Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting value of checkbox using angular

I have a problem with getting values of checkbox in angular. Here is the snippet:

<div class="list-group-item" *ngFor="let ticket of tickets">
   <input
      type="checkbox"
      [name]="ticket.id"
      [id]="ticket.id"
      [value]="ticket.id"
      formControlName="ticketTypes"
   />
   <label for="{{ ticket.id }}">{{ ticket.name }}</label>
</div>

I am getting above checkbox's value as true. How to get checkbox value correctly ?

Here is a stackblitz

like image 947
batgerel.e Avatar asked Oct 21 '25 02:10

batgerel.e


2 Answers

You can use (change) which fires every time when change detects on the input element and then write a custom logic to get the checked items from list, for example:

HTML:

<div class="list-group-item" *ngFor="let ticket of tickets">
    <input type="checkbox" [name]="ticket.id" [id]="ticket.id" [value]="ticket.id" (change)="onCheck(ticket.id)"/>
    <label for="{{ ticket.id }}">{{ ticket.name }}</label>
</div>

<pre>{{tickets | json}}</pre>

TS Code:

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  tickets = [{ id: 1, name: "Test1" }, { id: 2, name: "Test2" }];

  checkedTickets = [];

  onCheck(evt) {
    if (!this.checkedTickets.includes(evt)) {
      this.checkedTickets.push(evt);
    } else {
      var index = this.checkedTickets.indexOf(evt);
      if (index > -1) {
        this.checkedTickets.splice(index, 1);
      }
    }
    console.log(this.checkedTickets);
  }
}

Working Demo

like image 115
Adrita Sharma Avatar answered Oct 23 '25 18:10

Adrita Sharma


In such scenarios better/recommended to use formArray if you are dealing with the form or you can use simply ngModel two way data binding of Angular.

 <form [formGroup]="form" (submit)="submit(form.value)">
  <div *ngFor="let s of addOns.controls; let j=index">
   <input type="checkbox" [formControl]="s"/> {{user1.addOns[j].name}}
  </div>
 </form>

Also simply formControlName i.e single control is generally used while dealing with Radio Buttons because in that case user can select always single value but here in case of checkboxes you can select multiple entries as well, which is designed like this, So you might use array in that case like above in my example.

Working Example

Or in case you want to use ngModel you can use it like this -

<ul>
    <li *ngFor="let item of list">
    <input type="checkbox" [(ngModel)]="item.checked">{{item.title}}
  </li>
</ul>

Working Example

like image 21
Pardeep Jain Avatar answered Oct 23 '25 18:10

Pardeep Jain