简体   繁体   English

更新表单值返回未定义

[英]Updating a form value returns undefined

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这是 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?如何更新此表单值?

You can directly take value from form or get json value and use that.您可以直接从表单中获取值或获取 json 值并使用它。 The issue seems to be with assigning value for pfc问题似乎在于为 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")
              }
          });

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")
              }
          });

If this.pfc maps to this.participantForm.controls which seems to be a formgroup.如果this.pfc映射到this.participantForm.controls这似乎是一个表单组。 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.当您访问this.pfc.consent.consentDate.value时,您正在尝试访问( this.pfc as FormGroup).consent ,这是未定义的,因为FormGroup本身没有同意字段。 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

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

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