angular - 如何从数组中为Angular中的表单创建动态名称?
问题描述
我需要发送一个动态的表单,但我不知道如何为表单创建名称。
这是我的代码:
TS
export class MiPage implements OnInit {
public inputs = [];
FormData: any;
DataForm: FormGroup = new FormGroup({});
payLoad: any;
constructor() { }
generateFormControls(formData: any)
{
let tempGroup: FormGroup = new FormGroup({});
formData.forEach(i=>{
console.info(i.name);
tempGroup.addControl(i.name, new FormControl(''))
})
return tempGroup;
}
PreviewData()
{
this.payLoad = JSON.stringify(this.DataForm.value);
}
data() {
for (let numero of resp.datos){
this.inputs[numero.id_producto]=numero.id_producto; //the array
}
//So I manually create the names, but this is dynamic because it is generated from a query in the database
this.FormData = [
{
name:'429'
},{
name:'428'
}]
//But I need to create it dynamically. For example, but it gives me syntax error un "For"
this.FormData = [
for(let datos of this.inputs) {
name: datos
}
]
}
}
非常感谢,希望你能帮到我。并知道是否可以这样做,或者我如何动态创建名称
解决方案
您可能会将push
元素放入数组中。
this.FormData = [];
for(let datos of this.inputs) {
this.FormData.push({name: datos});
}
或者以更简洁的方式使用map
,正如@Eliseo 在下面的评论中所建议的那样:
this.FormData = this.inputs.map(x => ({name:x}));
推荐阅读
- shell - Shell - 如何在 for 循环中从文件中提取和替换值
- android - Fabric Beta:组织之间的渠道冲突?
- extjs - 6.5.3 经典 - 可以在图表轴标签上添加工具提示吗?
- c - 整数提升如何在 C Cast 上工作?
- sql - 在从数据库选择中检索 xmltype 时需要帮助
- python - 如何从csv中删除一列?
- assembly - WebAssembly 如何在任何机器上运行?
- android - 如何在 React Native 中正确修剪用户输入?
- javascript - 如何正确更新 Vuex 商店?
- jquery - Jquery 变量在 html 中显示 [object Object] 但在 console.log 中显示正确的值