I need to send a form dynamic but I don't know how create the names for the Form.
This is my code:
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
}
]
}
}
Thank you very much, I hope you can help me. And know if this if it's possible to do it like this or how I can dynamically create the names
You might push
the elements into the array.
this.FormData = [];
for(let datos of this.inputs) {
this.FormData.push({name: datos});
}
or in a more concise way using map
, as suggested by @Eliseo in the comment bellow:
this.FormData = this.inputs.map(x => ({name:x}));