Confused about how to convert a boolean to a number
Issue :
I'm struggling trying to convert my registerForm.value.aleas
, which is a checkbox, into a number (0 for false, 1 for true) in order to perform a POST request (the API expects values of either 1 or 0). However, I'm having difficulty achieving this as registerForm.value
always returns the default value (false if the checkbox isn't clicked and true if it is).
Attempts Made :
I attempted using ? 1 : 0
, but I don't think registerForm
accepts it and I haven't found another solution yet.
Sample Code :
app.component.ts
postParams(){
const token = JSON.parse(window.localStorage.getItem('token'));
const aleas = this.registerForm.value.aleas? 1 : 0;
return this.httpClient.post(`this.url?token=`,
{
token: token.token,
is_alea_chantier: aleas,
})
.subscribe(
data => {
console.log("POST PARAMS DONE",data)
},
error => {
console.log("POST PARAMS FAILED", error)
}
)
}
get f() {
return this.registerForm.controls;
}
onSubmit{
this.submitted = true;
console.log(this.registerForm.value.title)
//stop here if form is invalid
if (this.registerForm.invalid){
console.log("INVALID FORM")
return;
} else {
console.log("VALID FORM")
this.postParams();
}
}
app.component.html
<div class="container">
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()" >
<input formControlName="aleas" type="checkbox" class="custom-control-input" id="customCheck"
name="example1">
</form>
</div>
If you have any suggestions or guidance on how to solve this issue, please let me know. Your time is greatly appreciated!
EDIT
All the responses provided were helpful, but it appears there may be a backend issue now. Thank you!