Here's how I retrieve data from API and bind on FormGroup elements in angular:
this.api.GetRecipe(id).subscribe((data) => {
this.form = this.fb.group({
nome: [data.nome, [Validators.required]],
ingredienti: this.fb.group({
acqua: [data.ingredienti.acqua, [Validators.required]]
})
});
});
but I don't know how to bind in case of array. Such as retrieve farine
there (which is an array of objects):
this.api.GetRecipe(id).subscribe((data) => {
this.form = this.fb.group({
nome: [data.nome, [Validators.required]],
ingredienti: this.fb.group({
acqua: [data.ingredienti.acqua, [Validators.required]],
farine: this.fb.array([
this.fb.group({
quantita: [data.ingredienti.farine[x].quantita, [Validators.required]],
forza: [data.ingredienti.farine[x].forza, [Validators.required]]
})
])
})
});
});
of course [x]
isn't anywhere. Where do I retrieve x on every iteration? Or what's the way to propagate data from API to each FormGroup? Lambda?
CodePudding user response:
Use map method to create array of formGroup
this.api.GetRecipe(id).subscribe((data) => {
this.form = this.fb.group({
nome: [data.nome, [Validators.required]],
ingredienti: this.fb.group({
acqua: [data.ingredienti.acqua, [Validators.required]],
farine: this.fb.array(
data.ingredienti.farine.map(ingredient=>(
this.fb.group({
quantita: [ingredient.quantita, [Validators.required]],
forza: [ingredient.forza, [Validators.required]]
})))
)
})
});
});