lundi 5 décembre 2016

Angular2 - Dynamic FormArray for checkboxes

I build a Form in angular2 and typescript. I try to add a list of checkboxes dynamically and it's not working for me, Where is my mistake?

The template code:

<div formArrayName="categories">
   <div class="form-group" *ngFor="let category of updateDetailsForm.controls.categories.controls; let i = index">
      <label>
        <input type="checkbox" formControlName="{‌{i}}">
          {‌{category.name}}
      </label>
   </div>
</div>

The Typescript code:

updateDetailsForm: FormGroup;
private categories : Category[] = []

constructor(private router: Router,
            private ss : SearchService,
            private formBuilder: FormBuilder)
{
   this.initForm() // before the categories loaded
   this.ss.getAllCategories().subscribe(
     data => {
       this.categories = data
       this.initForm() // refresh the form with categories
     }
   )
 }

initForm() {
  let allCategories: FormArray = new FormArray([]);
  for (let i = 0; i < this.categories.length; i++) {
    allCategories.push(
      new FormGroup({
        'name': new FormControl([this.categories[i].categoryName])
      })
    )
  }
  this.updateDetailsForm = this.formBuilder.group({
    'image' : [''],
    'categories': allCategories
  })
}

This is my UI result, and I get the following error:

"inline template:17:33 caused by: control.registerOnChange is not a function"

enter image description here

The number of checkboxes is correct but the text is missing and I can't update the form result with user selection.

  1. What the error means?

  2. How can I insert the right text next the checkbox?

  3. How can update the user selection into the form value?

Aucun commentaire:

Enregistrer un commentaire