我在下面显示的dix部分设计了一个表单数组。
<div class="row">
<div class="col-xs-12" formArrayName="ingredients">
<div class="row"
*ngFor="let ingredientCtrl of getControls(); let i = index"
[formGroupName]="i" style="margin-top: 10px;">
<div class="col-xs-8">
<input type="text"
formControlName="name"
class="form-control">
</div>
<div class="col-xs-2">
<input type="number"
formControlName="amount"
class="form-control">
</div>
<div class="col-xs-2">
<button type="button" class="btn btn-danger">X</button>
</div>
</div>
</div>
</div>
打字稿部分
let recipeIngredients = new FormArray([]);
if (recipe['ingredients']) {
for (let ingredient of recipe.ingredients) {
recipeIngredients.push(
new FormGroup({
name: new FormControl(ingredient.name),
amount: new FormControl(ingredient.amount)
})
);
}
}
getControls() {
return (this.recipeForm.get('ingredients') as FormArray).controls;
}
在打字稿部分,我有一个关于以食谱成分和成分命名的变量的问题。
[tslint] Identifier 'recipeIngredients' is never reassigned; use 'const' instead of 'let'. (prefer-const)
[tslint] Identifier 'ingredient' is never reassigned; use 'const' instead of 'let'. (prefer-const)
我试图从成分中获取值并将其设置为输入字段,但是这样会引发错误。
ERROR Error: Cannot find control with name: 'ingredients'
我该如何解决?
答案 0 :(得分:2)
您应该在模板中添加主 formGroup ,然后添加主模板的 formArrayName ,然后在每个formArray项中添加 formGroupName ,表单应为:>
ngOnInit(){
this.recipeForm = new FormGroup({
'ingredients':new FormArray([])
});
let recipeIngredients = new FormArray([]);
let recipe = {
ingredients : [{name: 'sdfsdf', amount: 2121}]
}
if (recipe['ingredients']) {
for (let ingredient of recipe.ingredients) {
(<FormArray>this.recipeForm.get('ingredients')).push(
new FormGroup({
name: new FormControl(ingredient.name),
amount: new FormControl(ingredient.amount)
})
);
}
}
}
getControls() {
console.log( (this.recipeForm.get('ingredients') as FormArray).controls)
return (this.recipeForm.get('ingredients') as FormArray).controls;
}
html:
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-md-offset-2 col-sm-offset-1">
<form [formGroup]="recipeForm" (ngSubmit)="onSubmit()">
<div formArrayName="ingredients">
<div class="row" *ngFor="let ingredientCtrl of getControls(); let i = index" [formGroupName]="i"
style="margin-top: 10px;">
<div class="col-xs-8">
<input type="text" formControlName="name" class="form-control">
</div>
<div class="col-xs-2">
<input type="number" formControlName="amount" class="form-control">
</div>
<div class="col-xs-2">
<button type="button" class="btn btn-danger">X</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>