angular - 更改 registerForm 值(布尔值到数字)
问题描述
所以我在理解如何将布尔值转换为数字时遇到了一个小问题
问题 :
我一直在尝试将我的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>
如果有人能以正确的方式引导我,请随时告诉我您是否需要其他任何东西,我真的很感激,谢谢您的宝贵时间!
编辑
每个答案都有效,但现在似乎是后端问题,谢谢!
解决方案
您有几种方法可以将布尔值转换为数字,可以在编译器和运行时使用,但您需要在此之前以正确的方式获取 formControl 的值。
const aleasFirst = this.registerForm.get("aleas").value ? 1 : 0; // your method
const aleasSecond = Number(this.registerForm.get("aleas").value);
const aleasThird = +this.registerForm.get("aleas").value; // unary operator
推荐阅读
- javascript - HTML 元素是否有原型(如 Element.prototype.myFunc)?
- mysql - 如何更改 SQL 查询结果中的某些值?
- javascript - 当浏览器垂直调整大小时,保持 div 在视图中
- flutter - 颤振信息不想出现在屏幕上
- typescript - 模块解析失败:HTMLSelectElement Typescript 上出现意外标记?
- pyqt5 - Pyqt5:qgraphicstextitem的输入法有问题
- react-native - 任务 :app:checkProdDebugAarMetadata 失败
- angular - Angular js数字格式逗号
- python - 如何解决错误“sqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用 5,提供了 8 个”
- r - 如何合并每个 ID 的波段以在 R 中创建两个多波段 TIFF?