Angular - Passing FormBuilder values to Array results in empty string values

857 Views Asked by At

I have a form that I fill out using Angular's FormBuilder. This is the FormBuilder representation in the component typescript file:

constructor(private Form: FormBuilder) { }

AddStatusBoxForm = this.Form.group({
    cpuTempTopic: [''],
    uptimeTopic: [''],
    timeTopic: [''],
  });

I want to create a data structure that I can put these form values into, like so:

array: any[] = [this.AddStatusBoxForm.get('cpuTempTopic')?.value, 
                  this.AddStatusBoxForm.get('uptimeTopic')?.value, 
                  this.AddStatusBoxForm.get('timeTopic')?.value];

However console logging the array, results in empty strings. Yet if I console log the FormBuilder values on their own they print out fine:

console.log(this.AddStatusBoxForm.get('cpuTempTopic')?.value) // prints out fine
console.log(this.AddStatusBoxForm.get('uptimeTopic')?.value)
console.log(this.AddStatusBoxForm.get('timeTopic')?.value)
console.log(this.array) // prints out empty string 

enter image description here

I can't figure out why this is the case, I can't seem to pass the FormBuilder values to any sort of data structure. I've also tried a Map and the same occurs where the passed in values seem to end up as empty strings in the data structure. Yet accessing the FormBuilder values on their own seems to work fine.

I've even tried to console log the type of the values from the FormBuilder which results in string:

console.log(typeof(this.AddStatusBoxForm.get('cpuTempTopic')?.value))

enter image description here

Any help with this would be appreciated.

1

There are 1 best solutions below

0
On

This is because initially all the properties of the FormBuilder are initialized with empty string so while storing their values into an array will result with empty string values. You need to subscribe to value changes of the FormGroup in order to update your array values in real time. You can refer the example below and bring modifications to your code accordingly.

addStatusBoxFormChangesSubscription: Subscription;

ngOnInit(): void {
this.addStatusBoxFormChangesSubscription = merge(
      this.AddStatusBoxForm.get('cpuTempTopic').valueChanges,
      this.AddStatusBoxForm.get('uptimeTopic').valueChanges,
      this.AddStatusBoxForm.get('timeTopic').valueChanges
    ).subscribe(() => (this.array = [this.AddStatusBoxForm.get('cpuTempTopic')?.value, 
                  this.AddStatusBoxForm.get('uptimeTopic')?.value, 
                  this.AddStatusBoxForm.get('timeTopic')?.value];));
}

ngOnDestroy(): void {
    this.addStatusBoxFormChangesSubscription?.unsubscribe();
  }

It is always a good practice to unsubscribe from the subscription when not working on the same page anymore. You can explore more about form group here FormGroup documentation.