所以我在理解如何将 bool 值转换为数字时遇到了一些问题
问题:
我一直在尝试将我的registerForm.value.aleas
(这是一个复选框)转换为数字(0 false,1 true),以执行POST
方法(API
期望 1 或 0 值),但自从 registerForm.value
总是返回我他的默认值(如果复选框没有被点击,则为 false;如果她点击了,则为 true )。
我尝试过的:
我尝试过使用? 1 : 0
但我不认为 registerForm
接受它,而且我没有看到任何其他方式
代码示例:
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>
如果您需要任何其他信息,请随时告诉我,如果有人可以引导我走上正确的道路,我将非常感激,感谢您的宝贵时间!
编辑
每个答案都有效,但现在似乎是后端问题,谢谢!
最佳答案
您需要使用正确的语法来访问表单控件中的值:
const aleas = this.registerForm.controls['aleas'].value ? 1 : 0;
关于angular - 更改 registerForm 值( bool 值到数字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59172071/