类型错误:无法读取未定义的多个窗体组的属性"setValue"



我使用多个formgroup特定值,在提交之前需要更改数据值。但获取错误TypeError:无法读取属性"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")

最新更新