Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form Control value becomes null OnSubmit when Disabled

I have the following Angular 7 form:

ngOnInit() {

  this.organizationId = 1; // Used for testing

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

}

In the HTML I am using a Select for OrganizationId. It is disabled as expected.

However on submit the value is null and not 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
    };

  }

}

Why is the logged value null and not 1?

I am using disabled just to avoid the user to change the value.

But I still need the value on submit ...

like image 821
Miguel Moura Avatar asked Oct 27 '25 10:10

Miguel Moura


1 Answers

As you noticed Angular ignores disabled form controls in the form object.

This can be easily fixed by using getRawValue(), which includes all form controls, disabled or not. So for example on your submit, you pass the form (NOT the form value) like so:

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

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

Note that all of this is happening using NgForms not ReactiveForms. You can change For ReactiveForms accordingly just by adding getRawValue() like: console.log(this.form.organizationId.getRawValue());

like image 88
Akif Hussain Avatar answered Oct 29 '25 00:10

Akif Hussain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!