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

Mig*_*ura 4 angular angular-reactive-forms angular7

我有以下 Angular 7 形式:

ngOnInit() {

  this.organizationId = 1; // Used for testing

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

}
Run Code Online (Sandbox Code Playgroud)

在 HTML 中我使用的是Selectfor 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
    };

  }

}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Aki*_*ain 5

正如您所注意到的,Angular 会忽略表单对象中禁用的表单控件。

使用 getRawValue() 可以轻松解决此问题,其中包括所有表单控件(无论是否禁用)。例如,在提交时,您传递表单(而不是表单值),如下所示:

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

onSubmit() {
  console.log(form.getRawValue())
}
Run Code Online (Sandbox Code Playgroud)

请注意,所有这一切都是使用 NgForms 而不是 ReactiveForms 发生的。您可以通过添加以下内容来相应地更改 ReactiveForms getRawValue()console.log(this.form.organizationId.getRawValue());