form.valueChanges doesn't emit values for disabled controls
Asked Answered
U

3

23

I have an Angular Reactive form. I subscribe to its value changes and will emit changes to parent component. Some of the controls might get disabled by the user. The problem is that values from disabled controls are missing when form valueChanges are emitted. I've set a basic example.

When the checkbox is checked and the email input is disabled, there is no form control value logged. But I'd like to get ALL form values.

Underbody answered 27/12, 2017 at 13:17 Comment(1)
In Reactive forms angular ignores values having disabled.Retarder
A
39

Use the FormGroup's getRawValue() to include control values regardless of enable/disable state.

More information in the API documentation

this.myForm.valueChanges.subscribe(() => {
    this.formValues =  JSON.stringify(this.myForm.getRawValue());
});

Here is the forked example

Asia answered 27/12, 2017 at 13:35 Comment(0)
I
4

The value from a disable input is ignored (try to submit a form with a disabled input: it won't be posted).

You can change it to 'readonly'

<input formControlName="email" [readonly]="cb.checked">
<input #cb type="checkbox" formControlName="toggleEmail">

Updated example.

Ithaca answered 27/12, 2017 at 13:28 Comment(0)
W
3

this.form.valueChanges
      .pipe(map((_) => this.form.getRawValue()))
      .subscribe(res => {
        console.log(res)
      });
Wager answered 6/1, 2023 at 10:27 Comment(2)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Eaglewood
This is actually a very nice solution - it just lacks of explanation. The idea here is to "replace" the value coming from .valueChanges, and maps it to the raw values (which include disabled fields). By that, by subscribing on .valueChanges, you get all the fields (including disabled). Nice solution!Kraken

© 2022 - 2024 — McMap. All rights reserved.