我正在尝试为具有嵌套动态输入成分的食谱构建表单。我不知道我做错了什么。这是浏览器控制台的错误:
Cannot find control with path: 'ingredients -> 0 -> 0'
这是我的html
<div formArrayName="ingredients">
<div *ngFor="let ingredient of recipeForm.get('ingredients')['controls']; let i=index" [formGroupName]="i">
<!-- address header, show remove button when more than one address available -->
<div>
<span>Zutat {{i + 1}}</span>
<!-- <span *ngIf="recipeForm.get('ingredients')['controls'].length > 1" (click)="removeIngredient(i)">
</span> -->
</div>
<!-- Angular assigns array index as group name by default 0, 1, 2, ... -->
<div [formGroupName]="i">
<!--ingredient-->
<div [formGroup]="ingredient">
<div class="form-group col-xs-6">
<input type="text" class="form-control" formControlName="newIngredient">
</div>
<div class="btn btn-success" (onclick)="addIngredient()">neue Zutat</div>
</div>
</div>
</div>
</div>
这是我的 ts 文件
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validator, Validators } from '@angular/forms';
import { NewRecipe } from '../recipe.interface';
import { validateConfig } from '@angular/router/src/config';
@Component({
selector: 'app-recipe-creator',
templateUrl: './recipe-creator.component.html',
styleUrls: ['./recipe-creator.component.css']
})
export class RecipeCreatorComponent implements OnInit {
constructor(private formBuilder: FormBuilder) {}
recipeForm: FormGroup;
ingredients: FormArray;
instructions: FormArray;
ngOnInit() {
this.recipeForm = this.formBuilder.group({
name: '',
category: '',
prep_time: 0,
cooking_time: 0,
price: 0,
ingredients: this.formBuilder.array([this.createIngredient()]),
instructions: this.formBuilder.array([this.createInstruction()])
});
}
createIngredient(): FormGroup {
return this.formBuilder.group({
newIngredient: ['']
});
}
createInstruction(): FormGroup {
return this.formBuilder.group({
newInstruction: ['']
});
}
addIngredient(): void {
this.ingredients = this.recipeForm.get('ingredient') as FormArray;
this.ingredients.push(this.createIngredient());
}
addInstruction(): void {
this.instructions = this.recipeForm.get('instruction') as FormArray;
this.instructions.push(this.createInstruction());
}
saveRecipe() {}
removeIngredient(i) {}
}
我对角度很陌生,这让我发疯。所有表单的教程都有Angular 6似乎不支持的代码。是否有关于任何地方的FormArray嵌套表单的更新教程?
提前致谢。