0

我有一个使用 Angular 的FormBuilder填写的表格。这是组件打字稿文件中的FormBuilder表示:

constructor(private Form: FormBuilder) { }

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

我想创建一个可以将这些表单值放入的数据结构,如下所示:

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

但是,控制台记录数组会导致空字符串。但是,如果我自己控制台记录FormBuilder值,它们会打印出来:

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 

在此处输入图像描述

我不知道为什么会这样,我似乎无法将FormBuilder值传递给任何类型的数据结构。我也尝试了一个Map,同样的情况发生在传入的值似乎最终在数据结构中作为空字符串。然而,自行访问FormBuilder值似乎工作正常。

我什至尝试控制台记录来自FormBuilder的值的类型,这会导致字符串:

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

在此处输入图像描述

对此的任何帮助将不胜感激。

4

1 回答 1

0

这是因为最初FormBuilder的所有属性都是用空字符串初始化的,因此在将它们的值存储到数组中时,将产生空字符串值。您需要订阅FormGroup的值更改,以便实时更新您的数组值。您可以参考下面的示例并相应地对您的代码进行修改。

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();
  }

当不再在同一页面上工作时,取消订阅始终是一个好习惯。您可以在此处探索有关表单组的更多信息FormGroup 文档

于 2021-08-25T10:54:26.740 回答