问题
I'm working on a model driven form and I can't get it to add items to a list being displayed with ngFor. I'm currently getting an error when trying to iterate the list.I tried all solutions available.
Error
Cannot find control with path: 'categories -> 0'
ts file
private categories : any= [{name: 'Strict',selected : false},
{name: 'Moderate',selected : true},
{name: 'Flexible',selected : true}];
let allCategories: FormArray = new FormArray([]);
for (let i = 0; i < this.categories.length; i++) {
let fg = new FormGroup({});
fg.addControl(this.categories[i].name, new FormControl(this.categories[i].selected))
allCategories.push(fg)
}
form initialization
categories: allCategories,
Html part
<div formArrayName="categories">
<div *ngFor="let category of categories; let i=index">
<span formGroupName="{{i}}">
<label>
<input type="checkbox" formControlName="{{category.name}}"/>
{{category.name}}
</label>
</span>
</div>
</div>
回答1:
@Jadoon, I suppose, @DineshArun meant that he wants to list all categories using reactive approach and uses for that FormArray with FormGroups for each category. The problem is that Angular usually assigns array index as group name by default 0, 1... But in @DineshArun's case that doesn't work. And in mine case it didn't too, but I've found the solution.
First of all, look at this question and it's marked answer. Rewrite the filling in of your formArray that way, and then assign to formControlName
the raw name of the control, which you pointed in your patch()
method.
来源:https://stackoverflow.com/questions/44540453/cannot-find-control-with-path-angular2