繁体   English   中英

在 Angular 12 反应形式中使用 patchValue 绑定表单数组的最佳方法

[英]Best way to bind form array using patchValue in Angular 12 reactive form

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

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

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

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

演示

使用文档中定义的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);

您需要将 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,
    }))
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM