angular - 更改 registerForm 值( bool 值到数字)

标签 angular typescript angular-reactive-forms

所以我在理解如何将 bool 值转换为数字时遇到了一些问题

问题:

我一直在尝试将我的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>

如果您需要任何其他信息,请随时告诉我,如果有人可以引导我走上正确的道路,我将非常感激,感谢您的宝贵时间!

编辑

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

最佳答案

您需要使用正确的语法来访问表单控件中的值:

const aleas = this.registerForm.controls['aleas'].value ? 1 : 0;

关于angular - 更改 registerForm 值( bool 值到数字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59172071/

相关文章:

angular - 无法以 Angular 安装 Bootstrap

angular - 从 Angular 和 Spring MVC API 下载文件

Angular Material 选项卡内的 Angular react 形式给出错误

angular - 如何使用“ADDMORE”按钮在 Angular 6 中上传多个文件?

typescript - 如何在 typescript monorepo 中导入本地包

angular - 在 blur 上更新表单值并在 Angular 中提交

javascript - 如何使用 Chart.js 创建甘特图并填充日期?

angular - HttpClient 不返回数据

javascript - 为什么 push 显示 argument of type 'any[]' is not assignable to parameter of type 'never' 错误?

javascript - NextJS - `dev` 不工作,但 `build` && `start` 工作