【问题标题】:How to pass additional data to a reactive dynamic form in Angular如何将附加数据传递给 Angular 中的响应式动态表单
【发布时间】:2018-09-17 12:41:25
【问题描述】:

我有一个包含可编辑(将是formControl 对象)和只读数据(将是 HTML 上的静态文本)组合的数组。有没有办法在 Angular 中做到这一点?我也可以使用FormArraysFormGroups 添加这个静态文本,但感觉不对。让我用一个例子来详细说明这个问题:

说,我有一个 JSON 对象如下:

itemArray = [{
  title: 'fancy item', // not a member of the form (read-only)
  quantity: 0 // member of the form (editable)
},
{
  title: 'weird item', // not a member of the form (read-only)
  quantity: 1 // member of the form (editabe)
}
]

我将 FormArrays 用于项目的 quantity 字段。

this.formItems = new FormArray([
      new FormGroup(
        {
          quantity: new FormControl(1, Validators.required),
          title: new FormControl('Fancy item') // Readonly text for form group. What's the best way to add a enrichment data for a form group?
        }
      ),
      new FormGroup(
        {
          quantity: new FormControl(1, Validators.required),
          title: new FormControl('Weird item') // Readonly text for form group. What's the best way to add a enrichment data for a form group?
        }
      )
    ]
);

但是,标题不是可编辑的项目。向FormGroup 添加额外数据的最佳方式是什么?

否则,我必须创建另一个名为 items 的单独数组来管理这些额外且不可编辑的数据。因此,我可以将 item 的字段拆分为两个单独的对象。 1)staticDataForItems,2)editableDataForItems

this.staticDataForItems = [{
    title: 'Weird item',
  }
];

this.editableDataForItems = new FormArray([
      new FormGroup(
        {
          quantity: new FormControl(1, Validators.required),
        }
      ),
      new FormGroup(
        {
          quantity: new FormControl(1, Validators.required),
        }
      )
    ]
);

这是我不喜欢的解决方案。因为,在我的用例中,我可以将项目添加到数组或从数组中删除“项目”。我不想处理不是面向未来的 2 个数组(items 和 formArray)。

如果我有只读(只读 HTML 元素)和可编辑数据(输入 HTML 元素)数据的组合,我如何将这两个数组组合成 1 个单个数组。

我既想从表单验证中受益,又想以一种好的方式添加额外的数据。

您可以在下面找到一个工作示例:

https://stackblitz.com/edit/angular-gw1c6d?file=app%2Fapp.component.ts

谢谢。

【问题讨论】:

  • 所以你希望标题控件是只读的,但在使用formItems[someIndex].value时仍然是表单组值的一部分?
  • @Jota.Toledo 我什至不想让“title”成为 formControl,因为它不是控件。它只是一个包含项目描述信息的静态文本。

标签: angular angular-reactive-forms formarray formgroups


【解决方案1】:

我只是像这样在提交函数中传递静态值:

`<form [formGroup]="prodForm" (ngSubmit)="onAddToCart(
    product._id, 
    product.title, 
    product.price, 
    product.sale,
    prodForm.value)">`

然后 prodForm.value 保存项目的大小、颜色和数量的控件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 2018-09-01
    • 1970-01-01
    • 2019-04-11
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多