2

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
    Please clarify your specific problem or add additional details to highlight exactly what you need. –  Jun 14 '17 at 09:17
  • A few questions, why do you need to iterate through the form if you only have 3 checkboxes? what is `allCategories` used for? what does the class `FormArray` looks like and why don't you just use an array of `FormControls`? – Daniel Ormeño Jun 16 '17 at 05:29
  • 1
    @jadoon, i am trying to implement the reactive forms for my application.. on the submission, i am getting json format n being saved in mongo.. now i want to build the form using json. Where I am struggling with iteration of form arrays.. patchValue will work only with simple json. I want patch like array of json in below format – Dinesh Arun Jun 17 '17 at 05:02
  • Format { name : 'Dinesh', dob : '02/04/1991', addreses : [ { line1 : 'line1' }, {line2 : 'line2'}]}.. can you help me how to do this ? – Dinesh Arun Jun 17 '17 at 05:07

1 Answers1

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.

Markiza
  • 444
  • 1
  • 5
  • 18