繁体   English   中英

TypeError:无法读取未定义的多个表单组的属性“setValue”

[英]TypeError: Cannot read property 'setValue' of undefined multiple form group

我正在使用多个表单组特定值,我需要在提交之前更改数据值。 但得到错误 TypeError: Cannot read property 'setValue'

    this.setUpForm = this.formBuilder.group({
          MorningSpan: this.formBuilder.group({
            StartTime: ['00:00'],
            EndTime: ['11:59'],
          }),
        });
    onSubmit(){
      this.setUpForm.get['MorningSpan.StartTime'].setValue("24:00")
}

您的问题是因为您使用的是 [] 而不是 ()。 试试看: this.setUpForm.get('MorningSpan.StartTime').setValue("24:00")

多种方法,但我想你正在寻找这个:

onSubmit(){
  this.setUpForm.get(['MorningSpan', 'StartTime']).setValue('24:00');
}

你基本上传入一个路径数组

另一种方法是调用get两次,但这可能会因路径很深而变得不确定:

onSubmit(){
  this.setUpForm.get('MorningSpan').get('StartTime').setValue('24:00');
}

当然,您也可以使用点限制路径:

onSubmit(){
  this.setUpForm.get('MorningSpan.StartTime').setValue("24:00");
}

但个人意见明智,我更喜欢数组方法,因为它使您能够(如果您喜欢这类事情)使其对您的表单完全安全。 虽然您需要编写一些额外的代码,但它也会使重构更容易。 要记住的事情:)

有 4 种不同的方法可以做到这一点: 您可以使用以下任何一种:

1) this.setUpForm.get(['MorningSpan', 'StartTime']).setValue("24:00")

2) this.setUpForm.get('MorningSpan').get('StartTime').setValue("24:00")

3) this.setUpForm.controls['MorningSpan'].controls['StartTime'].setValue("24:00")

4) this.setUpForm.controls.MorningSpan.controls.StartTime.setValue("24:00")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM