Ionic3/Angular Error: Must supply a value for form control with name: 'jobStatus'

My problem was that I wasn't providing all form controll values. For example:

<div formGroupName="form">
    <input formControlName="first">
    <input formControlName="second">
</div>

In this case, if you try to use method setValue and do not provide all controll values, like this:

this.form.setValue({ second: "" });

it will throw an error.

Solution

Either use setValue and provide value for all form controls:

this.form.setValue({ first: "", second: "" });

or, if you really intend to set partial values, use patchValue method:

this.form.patchValue({ second: "" });

"Must provide" tells you to pass a value to object on the Form. Ex:

Imaginate this scenario:

  public form = this.fb.group({
    production: this.fb.group({
      name: [''],
      id: [''],
      screenName: [''],
    })
  });

When you receive this data from server, the form wait 3 objects... "name", "id" and "screenName". And PatchValue works fine.

But, if you received data, you only have 2 objects: "name" and "screen name", and you try to do:

const formProduction = this.form.get('production');
formProduction.patchValue(this.yourData);

You can receive this message about "Must Apply", because the form wait all data. This happen to, if you force a Cast, like this:

const formProduction = this.form.get('production');
formProduction.patchValue(this.yourData as YourObject);

In this case in top of discuss, private jobStatus:number causes the same error.

A easy way to fix it is casting as unknown: If you server don't send all info, angular put in form only infos received, and ignore other fields.

const formProduction = this.form.get('production');
formProduction.patchValue(this.yourData as unknown);

;-)


You could also use patchValue to just set one or more inputs individually:

this.form.patchValue({ first: "whatever" });

Right... I had a form that used to only have a single form control, called 'comment'.

When I added a second, conditional form element, the syntax you need to use changes for setValue...

I needed to modify it from something like this:

  this.modalFG.setValue({'comment': data.comment});
  this.modalFG.setValue({'jobStatus': 0});

to:

  this.modalFG.controls['jobStatus'].setValue(0);
  this.modalFG.controls['comment'].setValue(data.comment);

because I now had two fields on the form...

Then everything fell into place and the misleading message about not having supplied form field disappeared.

I hate the syntax of Angular here, changing it's functioning behaviour when you go from 1 to n values!