Reputation: 1207
This is my component code
this.participantForm = this.fb.group({
occupation: [null],
consent : new FormGroup({
consentBy: new FormControl(''),
consentDate: new FormControl(new Date())
})
})
This is the 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>
On submit I need to format the Date value.
get pfc() {
return this.participantForm.controls;
}
this.participantForm.patchValue({
consent: {
consentDate : moment(this.pfc.consent.consentDate.value, "DD-MMM-YYY HH:mm").format(
"DD-MMM-YYYY HH:mm")
}
});
This throws error
ERROR TypeError: Cannot read property 'consentDate' of undefined.
Here consent is undefined. How can I update this form value ?
Upvotes: 0
Views: 722
Reputation: 654
If this.pfc
maps to this.participantForm.controls
which seems to be a formgroup. When you access this.pfc.consent.consentDate.value
, you are trying to access (this.pfc as FormGroup).consent
, which is undefined since FormGroup
itself does not have the consent field. That is why you are getting the error.
To access the value properly, you need to use
this.pfc.value.consent.consentDate
or
this.pfc.get('consent.consentDate').value
Upvotes: 0
Reputation: 542
You can directly take value from form or get json value and use that. The issue seems to be with assigning value for 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")
}
});
Upvotes: 1
Reputation: 1780
Use below code to get form value.
this.participantForm.patchValue({
consent: {
consentDate : moment(this.pfc.get("consent").get("consentDate").value, "DD-MMM-YYY HH:mm").format(
"DD-MMM-YYYY HH:mm")
}
});
Upvotes: 0