Search code examples
javascriptangulartypescriptangular7

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


Solution

  • 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