首页 > 解决方案 > 更改 registerForm 值(布尔值到数字)

问题描述

所以我在理解如何将布尔值转换为数字时遇到了一个小问题

问题 :

我一直在尝试将我的registerForm.value.aleas哪个复选框转换为一个数字(0 false,1 true),以执行一个POST方法(API期望10值),但我找不到这样做的方法,因为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>

如果有人能以正确的方式引导我,请随时告诉我您是否需要其他任何东西,我真的很感激,谢谢您的宝贵时间!

编辑

每个答案都有效,但现在似乎是后端问题,谢谢!

标签: angulartypescriptangular-reactive-forms

解决方案


您有几种方法可以将布尔值转换为数字,可以在编译器和运行时使用,但您需要在此之前以正确的方式获取 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

推荐阅读