我有一个数组,其中包含可编辑的(将是formControl
对象)和 read-only data(will 是 HTML 上的静态文本。有没有办法在 Angular 中做到这一点?我也可以使用FormArrays
和FormGroups
添加这个静态文本,但感觉不对。让我用一个例子详细说明问题:
说,我有一个 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
的独立数组来管理这个额外的和 non-editable 数据。因此,我可以将项目的字段拆分为两个单独的对象。 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),
}
)
]
);
这是我不喜欢的解决方案。因为,在我的用例中,我可以向数组添加项目或从数组中删除“items”。我不想处理不是 future-proof 的 2 arrays(items 和formArray
。
如果我有 read-only(read-only HTML 元素的组合和可编辑的 data(input HTML 元素)数据,我该如何将这两个数组合并为 1 个单个数组。
我想要从表单验证中受益,我想以一种好的方式添加其他数据。
您可以在下面找到一个工作示例:
https://stackblitz.com/edit/angular-gw1c6d?file=app %3
谢谢。
1 回答
我只是在提交函数中传递静态值,如下所示:
然后 prodForm.value 保存项目的大小,颜色和数量的控件。