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>

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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;

Comments

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

2 Comments

Its not working, I have tried this, but on uncheck its not set value 0.
@TarnjeetSingh updated but only with ngForm and its somehow its buggy on latest verion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.