禁用时,表单控件值在OnSubmit上变为空

时间:2019-06-07 15:56:32

标签: angular angular7 angular-reactive-forms

我有以下Angular 7表格:

ngOnInit() {

  this.organizationId = 1; // Used for testing

  this.form = this.formBuilder.group({     
    name: [''],
    organizationId: [{ value: this.organizationId, disabled: this.enableOrganizationChange }],
    start: ['']
  });

}

在HTML中,我为Select使用了OrganizationId。它已按预期禁用。

但是,提交时的值为null而不是1:

onSubmit() {

  if (this.form.valid) {

    this.submitting = true;

    console.log(this.form.value.organizationId);

    let request: Request = { 
      name: this.form.value.name,
      organizationId: this.form.value.organizationId.value,
      start: this.form.value.start
    };

  }

}

为什么记录的值是null而不是1

我使用禁用功能只是为了避免用户更改值。

但是我仍然需要提交的值...

1 个答案:

答案 0 :(得分:1)

您注意到Angular忽略了表单对象中禁用的表单控件。

可以使用getRawValue()轻松解决此问题,该方法包括所有窗体控件,无论是否禁用。因此,例如,在提交时,您像这样传递表单(不传递表单值):

(ngSubmit)="onSubmit(form)" 
Then you can use getRawValue:

onSubmit() {
  console.log(form.getRawValue())
}

请注意,所有这些都是使用NgForms而非ReactiveForms发生的。 您只需添加getRawValue()就可以相应地更改For ReactiveForms,例如:console.log(this.form.organizationId.getRawValue());

相关问题