我试图遍历组件中的formArray,然后在单击更新按钮时填充输入框,但是在运行时出现以下错误:-
错误:找不到具有未指定名称属性的控件
这是我的班级文件上的逻辑
recipe-edit.component.ts
export class RecipeEditComponent implements OnInit {
recipeform:FormGroup
id:number
editmode=false
constructor(private router:Router,private
route:ActivatedRoute,private reservice:Recipeservice) { }
ngOnInit() {
this.route.params.subscribe(
(params)=>{
this.id=+params['id']
this.editmode=true
this.initform()
}
)
}
private initform(){
let recipeingredients=new FormArray([])
if(this.editmode){
const recipe=this.reservice.getrecipe(this.id)
if(recipe.ingredients!=null){
for(let ingredient of recipe.ingredients){
recipeingredients.push(
new FormGroup({
'name':new FormControl(ingredient.name),
'amount':new FormControl(ingredient.amount)
})
)
}
}
}
this.recipeform=new FormGroup({
'ingredients':recipeingredients
})
}
onsubmit(){
console.log(this.recipeform)
}
}
这是我的html文件中的逻辑外观 recipe-edit.component.html
<div class="row">
<div class="col-xs-12">
<form [formGroup]="recipeform" (ngSubmit)="onsubmit()">
<div class="row">
<div class="col-xs-12" formArraynName="ingredients">
<div
class="row"
*ngFor="let ingredientctrl of
recipeform.get('ingredients').controls;let i=index"
[formGroupName]="'i'"
style="margin-top: 10px;">
<div class="col-xs-8">
<input
type="text"
class="form-control"
formControlName="name"
>
</div>
<div class="col-xs-2">
<input
type="number"
class="form-control"
formControlName="amount"
>
</div>
</div>
</div>
</div>
</form>