【问题标题】:angular set non-checked checkbox to false in serialized data在序列化数据中,角度将未选中的复选框设置为 false
【发布时间】:2020-02-10 10:51:45
【问题描述】:

我希望我的复选框被初始化为 false 而不是 NULL,因为表单只会在第一次选中和未选中时将复选框值设置为 false,否则它保持为空并且我收到此错误。

将值 {null} 转换为类型“System.Boolean”时出错。路径“inStock”,第 1 行,位置 84。

如何在 Angular 中使用模板表单将表单数据初始化为 false?

createRegisterForm() {
this.registerForm = this.fb.group({
  partname:['', Validators.required],
  partdescription : ['', Validators.required],
  parturl: ['',null],
  sku: ['',null],
  inStock: '',
  isActive: '' 
})

}

registerPart() {
if (this.registerForm.valid) {
  this.part = Object.assign({}, this.registerForm.value);
  this.partsService.add(this.part).subscribe(() => {
    this.alertify.success('Part Registered');
  }, error => {
    this.alertify.error(error);
  });
}

【问题讨论】:

  • 好吧,将 inStock 初始化为 false 而不是 ''
  • 如果我像你说的那样初始化为 false,则在加载时选中复选框
  • 不,不是:stackblitz.com/edit/angular-vhvmjb。您尚未发布的其他一些代码可以做到这一点。

标签: angular angular-template-form


【解决方案1】:

每次运行 reset 方法时,都会将 from 值设置为 null,在这种情况下,您可以像这样将值作为默认值设置为 false

this.registerForm.reset({
  inStock: false,
  isActive: false
});

并且你需要在创建过程中将初始值设置为 false 而不是空字符串,以防你不调用 rest 方法,就像上面一样。

createRegisterForm() {
this.registerForm = this.fb.group({
  partname:['', Validators.required],
  partdescription : ['', Validators.required],
  parturl: ['',null],
  sku: ['',null],
  inStock: false,
  isActive: false 
})
}

检查这个demo ⚡⚡,其中我涵盖了表单控件值可能最终为空的所有情况以及为什么要解决这个问题

【讨论】:

    猜你喜欢
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 2011-11-12
    • 2012-11-07
    • 2018-10-26
    • 2014-08-22
    • 2011-08-31
    相关资源
    最近更新 更多