简体   繁体   中英

How to get value of checkbox in 0/1 instead of true/false reactive forms angular4

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>

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); 

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 ">

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" />

Try this:

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

.ts

checkbox_checked: boolean;

state: number;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM