Search code examples
angularnullangular-materialangular-reactive-forms

Angular 6 getRawValue() will not return disabled values


I have an example form as follows:

 stuff: IStuff; 
 buildForm() {
        this.createForm = this.form.group({
            Val1: [{ value: '', disabled: true }],
            Val2: [{ value: '', disabled: true }]
        });

As you can see both values are set to disabled.

The constructor triggers a httpClient get and populates the model:

this.exampleHttpService.getStuff()
    .subscribe(stuff => this.stuff = stuff); 

Where stuff is:

export interface IStuff {
    Val1?: number; 
    Val2?: number
}

The binding is the done in the html for both Val1 and Val2 as follows:

  <input name="Val1" matInput formControlName="Val1" [value]="stuff?.Val1">

This is all god and it nicely assigns the values and displays them on the screen; however when I am trying to get those values back using

this.createForm.getRawValue()

I get '' empty strings for both values...

Any idea?


Solution

  • When you use reactive forms, the input value is already bound to the form control, you don't need to (and shouldn't) bind to the input's value as the value and the form control are not the same thing. In your code, you are initializing 'stuff' that is bound to the input values, but you aren't initializing the form control values. You need to initialize the form control values:

    this.exampleHttpService.getStuff()
        .subscribe((stuff) => {
            this.createForm.controls['Val1'] = stuff.Val1;
            this.createForm.controls['Val2'] = stuff.Val2;
        });