0

I am attempting to patch values into an initialized FormGroup once a component is loaded like so (where editForm is the FormGroup and editInfo is a JSON containing the information I want to patch into the form):

Object.keys(this.editForm.controls).forEach(key => {
                if ((key.includes("date") || key.includes("Date")) && this.editInfo[key] != undefined) {
                    this.editForm.patchValue({
                        key: {
                            date: {
                                year: this.editInfo[key].getFullYear(),
                                month: this.editInfo[key].getMonth() + 1,
                                day: this.editInfo[key].getDate()
                            }
                        }
                    });
                }
            });

For some reason, this is not patching any of the values. The if statement is running when it is supposed to, and all of the .getFullYear(), .getMonth(), and .getDate() values (all of these key values are Date objects) are defined and correct. When I replace

this.editForm.patchValue({
                            key: {
                                date: {

with

this.editForm.patchValue({
                            'specificKey': {
                                date: {

that key is patched correctly. Is there any reason why not specifying the key would cause this not to work? This is the module I am using for my datepickers (the values I am trying to patch above) if that is of any use.

Matthew Green
  • 10,161
  • 4
  • 36
  • 54
Wadoo9
  • 73
  • 1
  • 10

1 Answers1

1

Found my answer through this link (Is there a way to use variable keys in a JavaScript object literal?) provided by Ankit Saroch. The solution is to put [] around key when patching the value, like so:

this.editForm.patchValue({
                            [key]: {
                                date: {

With the brackets, the keys are interpreted like computed property names.

Wadoo9
  • 73
  • 1
  • 10