2

I have worked on angular4 project and I have a requirement where I need to get the value of checkbox in 0/1 instead of true/false. I mean if checkbox is checked then it will return 1 otherwise return 0. If anyone know the solution please guide me, thanks in advance.

<form [formGroup]="myForm">
    <input type="checkbox" formControlName="status" />
</form>
Tarnjeet Singh
  • 846
  • 1
  • 11
  • 30

4 Answers4

4

you can cast a boolean to number in this way:

  1. + operator: +var
  2. Number constructor as function: Number(var)
  3. https://stackoverflow.com/a/29543818/4099454

const success = true;
const failure = false;

console.log('success: ', success, '=>', +success);
console.log('failure: ', failure, '=>', +failure);
Hitmands
  • 13,491
  • 4
  • 34
  • 69
2

Just add it:

 (change)="status = $event.target.checked ? 1: 0"

Like:

 <input type="checkbox" 
   (change)="status = $event.target.checked ? 1: 0"
   name="status "
   [(ngModel)]="status ">
Imranmadbar
  • 4,681
  • 3
  • 17
  • 30
1

Try this:

<input 
    type="checkbox" 
    checked="checkbox_checked" 
    [(ngModel)]="checkbox_checked"
    (change)="checkbox_checked ? state = 1 : state = 0">

.ts

checkbox_checked: boolean;

state: number;

0

I have managed to make it work but only with ngForm plunker. On latest version it doesn't bind to value at all probably bug.

<input type="checkbox" (ngModelChange)="status = $event ? 1 : 0" [ngModel]="status" />
alexKhymenko
  • 5,450
  • 23
  • 40