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:
+
operator: +var
Number
constructor as function: Number(var)
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.