Angular - Add form values from a FormBuilder Form.group into a Map data structure

597 views Asked by At

I have a FormBuilder form group called AddStatusBoxForm:

AddStatusBoxForm = this.Form.group({
    name: ['']
  });

I then have a Map data structure which I think would have a type of Map<string, string>:

statusBoxValues = new Map<string, string>
  ([
    ['name', this.AddStatusBoxForm.get('name')?.value]
  ]);

The Map data structure takes in this.AddStatusBoxForm.get('name')?.value as the item in the map, with the key being the string 'name'.

I test a few things with console.log(). First I print out the type of the value retrieved from the AddStatusBoxForm which returns a type of string. Then I print out the actual value of the input in the form which returns that same value. Lastly I attempt to print out the first item in my statusBoxValues Map, which contains the same code used to retrieve values from the AddStatusBoxForm form group. However this returns empty string, when I expect it to return the value that was inputted into the form.

console.log(typeof(this.AddStatusBoxForm.get('name')?.value)) //returns string
console.log(this.AddStatusBoxForm.get('name')?.value) // returns value of input 
console.log(this.statusBoxValues.get('name')) // returns <empty string>

enter image description here

Would anyone be able to help me so that I could add the values from a Form Group into a Map data structure, or maybe an equalivant data strucuture that has key pair values?

Thanks.

1

There are 1 answers

0
Hedgybeats On

Your issue is that this.AddStatusBoxForm.get('name')?.value is firing, once and only once as you add it to the map.

Try this instead:

var statusBoxValues = {
  'name': () => this.AddStatusBoxForm.get('name')?.value,
  'otherName': () => this.AddStatusBoxForm.get('otherName')?.value,
};

You can then call the function like this:

this.statusBoxValues['name']();