Angular 更新表单值将返回未定义的值
这是我的组件代码Angular 更新表单值将返回未定义的值,angular,typescript,angular8,Angular,Typescript,Angular8,这是我的组件代码 this.participantForm = this.fb.group({ occupation: [null], consent : new FormGroup({ consentBy: new FormControl(''), consentDate: new FormControl(new Date()) }) }) 这是html <form [formGroup]="partici
this.participantForm = this.fb.group({
occupation: [null],
consent : new FormGroup({
consentBy: new FormControl(''),
consentDate: new FormControl(new Date())
})
})
这是html
<form [formGroup]="participantForm">
<div formGroupName="consent">
<label>
Name:
<input type="text" formControlName="consentBy">
</label>
<label>
Date:
<input type="text" formControlName="consentDate">
</label>
</div>
</form>
这会引发错误
ERROR TypeError: Cannot read property 'consentDate' of undefined.
这里没有定义同意。如何更新此表单值?使用以下代码获取表单值
this.participantForm.patchValue({
consent: {
consentDate : moment(this.pfc.get("consent").get("consentDate").value, "DD-MMM-YYY HH:mm").format(
"DD-MMM-YYYY HH:mm")
}
});
您可以直接从表单中获取值,或者获取json值并使用它。问题似乎在于为pfc赋值
const formData = this.participantForm.getRawValue();
this.participantForm.patchValue({
consent: {
consentDate : moment(formData.consent.consentDate, "DD-MMM-YYY HH:mm").format(
"DD-MMM-YYYY HH:mm")
}
});
如果
this.pfc
映射到this.participantForm.controls
,它似乎是一个表单组。当您访问this.pfc.approvement.approvementDate.value
时,您正试图访问(this.pfc as FormGroup).approvement
,它是未定义的,因为FormGroup
本身没有同意字段。这就是为什么会出现错误
要正确访问该值,需要使用
this.pfc.value.consent.consentDate
或
似乎这个.pfc.同意没有定义。如何创造价值?这是什么。pfc?我认为错误来自这里-this.pfc.approve.approvement日期。value@TonyMarko更新的pfc
this.pfc.value.consent.consentDate
this.pfc.get('consent.consentDate').value