当没有指定验证器时,FormGroup认为它是必需的

时间:2017-01-30 17:39:39

标签: angular angular2-forms

我有一个带有嵌套FormGroup的表单:

this.form = this.formBuilder.group({
  kitType: [
    '', [
      Validators.required,
    ]
  ],
  diagnosisCode: [
    '', [
      Validators.required,
    ]
  ],
  delayKitShipmentDate: new FormGroup({
    year: new FormControl(''),
    month: new FormControl({ value: '', disabled: true }),
    day: new FormControl({ value: '', disabled: true }),
  })
});

delayKitShipmentDate是可选的,并且没有在控件上指定任何验证器,但我的表单正在报告invalid,除非我指定年,月和日控件的值。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我已使用以下代码/模板进行了测试:

testForm:FormGroup;
constructor(public fb:FormBuilder) {
this.testForm = this.fb.group({
          kitType: [
            '', [
              Validators.required,
            ]
          ],
          diagnosisCode: [
            '', [
              Validators.required,
            ]
          ],
          delayKitShipmentDate: new FormGroup({
            year: new FormControl(''),
            month: new FormControl({ value: '', disabled: true }),
            day: new FormControl({ value: '', disabled: true }),
          })
        });
}

模板

<div  [formGroup]="testForm">
            kitType<input formControlName="kitType"  id="kitType"/>
            diagnosisCode<input formControlName="diagnosisCode"  id="diagnosisCode"/>
            <div formGroupName="delayKitShipmentDate">
              year<input  formControlName="year"  id="year"/>
              month<input  formControlName="month"  id="month"/>
              day<input  formControlName="day"  id="day"/>

            </div>
            <div>
              <p>Form: {{ testForm.value | json }}</p>
              <p>Form status: {{ testForm.status }}</p>
            </div>

          </div>

您的代码应该有效 testForm

@angular version:^ 2.4.4