Угловая патчана динамически
@Component({ selector: "app-edit-recipe", templateUrl: "./edit-recipe.component.html", styleUrls: ["./edit-recipe.component.css"], }) export class EditRecipeComponent implements OnInit { editRecipeF!: FormGroup; recipeId: any; selectedRecipe!: Recipe; constructor( private formBuilder: FormBuilder, private recipesService: RecipesService, private route: ActivatedRoute ) {} ngOnInit() { this.recipeId = this.route.snapshot.params["id"]; this.editRecipeF = this.formBuilder.group({ recipeDetails: this.formBuilder.group({ title: ["", Validators.required], imageUrl: ["", Validators.required], duration: ["", Validators.required], calories: ["", Validators.required], }), ingredients: this.formBuilder.array([this.createIngFormGroup()]), }); this.recipesService.fetchRecipeDetails(this.recipeId).subscribe( (selectedRecipeDetails) => { this.selectedRecipe = selectedRecipeDetails; this.editRecipeF.patchValue({ recipeDetails: { title: this.selectedRecipe.title, imageUrl: this.selectedRecipe.imageUrl, duration: this.selectedRecipe.duration, calories: this.selectedRecipe.calories, }, }); const ing = this.editRecipeF.get("ingredients") as FormArray; for (let ingredient of this.selectedRecipe.ingredients) { ing.patchValue([ { name: ingredient.ingName, qty: ingredient.ingQty, qtyUnit: ingredient.ingQtyUnit, imageUrl: ingredient.ingImageUrl, }, ]); } }, (error) => { console.log(error); } ); } private createIngFormGroup() { return new FormGroup({ name: new FormControl("", Validators.required), qty: new FormControl("", Validators.required), qtyUnit: new FormControl("", Validators.required), imageUrl: new FormControl("", Validators.required), }); } public getControls() { return (<FormArray>this.editRecipeF.get("ingredients")).controls; } public onAddIngredients() { const ingredients = this.editRecipeF.get("ingredients") as FormArray; ingredients.push(this.createIngFormGroup()); } public onSubmitEditRecipeForm() { if (this.editRecipeF.valid) { console.log(this.editRecipeF.value); this.recipesService .editRecipe(this.editRecipeF.value, this.recipeId) .subscribe( (success) => {}, (error) => { console.log(error); } ); } } }
Confused Chinchilla