【问题标题】:Best way to bind form array using patchValue in Angular 12 reactive form在 Angular 12 反应形式中使用 patchValue 绑定表单数组的最佳方法
【发布时间】:2022-01-03 21:03:34
【问题描述】:

我正在获取不同格式的数据,但在使用“拆分”之后,我最终得到了正确的响应值。现在控制台显示响应数据如下:

0:{ name: 'dev', label: 'actor' },
1:{ name: 'madhu', label: 'actress' },
 ......

现在我想在我的 formArray 中修补这些数据

我创建了一个演示以便更好地理解..

DEMO

【问题讨论】:

    标签: javascript angular formarray


    【解决方案1】:

    使用documentation中定义的patchvalue()

    // Get the data from the service or a placeholder defined here
    const dataFromService: Array<{name: string; label: string}> = [
      { name: 'dev', label: 'actor' },
      { name: 'madhu', label: 'actress' }
    ];
    // patch the form array with your data
    // as long as your data conforms to the names of the FormControls in your formArray, patchValue works
    form.patchValue(dataFromService);
    

    【讨论】:

    • 我尝试使用您的代码,但没有任何反应!也没有错误!
    • 我想如果我使用它没问题: const dataFromService: Array = this.data form.patchValue({id: this.id, reference: dataFromService })
    • 我同意@Edward 的观点,即使用 patchValue() 将是一个好习惯!请给我一些想法来摆脱这个问题..如果可能的话。
    【解决方案2】:

    您需要将 formGroup 推入 formArray,如下所示。任何时候你想添加数据,你都可以推入数组(你可以使用你做的扩展来获取表单控件'凭据')

     ngOnInit(): void {
        this.form = this.fb.group({
          credentials: this.fb.array(this.getData()),
        });
      }
    
      getData(): FormGroup[] {
        return this.data.map(d => this.fb.group({
          name: d.name,
          label: d.label,
        }))
      }
    

    【讨论】:

    • 在演示中它正在工作,但是当我尝试在实际应用程序中使用此代码时,它显示错误:ERROR TypeError: Cannot read properties of undefined (reading 'map')
    • 我的错,我在真实应用中获取点击事件的数据,而不是 oninit!
    • 现在它工作正常!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-08-26
    • 2017-09-11
    • 2018-10-26
    • 1970-01-01
    • 2021-02-08
    • 2019-04-24
    • 2020-04-22
    • 2021-02-17
    相关资源
    最近更新 更多