7

I have a dynamic size of items. For every item I want to generate a checkbox. I thought the best approach for that is to use the FormArray.

But I cannot set any additional property to specifiy the label for the dynamic checkboxes.

items: Array<string> = ['Banana', 'Apple', 'Beer', 'Water'];

let checkboxArray = new FormArray([]);

this.items.forEach(item => {
  let formControl = new FormControl(true);
  checkboxArray.push(formControl);
})

But as we see here, i can only specifiy the value for the checkbox in the formControl, but cannot set any additional info about the label.

A working plunkr is here: http://plnkr.co/edit/ODe5QSOEvQsQiuBzs56o?p=preview

2 Answers 2

20

Use normal FormGroup.

form: FormGroup;
items: string[] = ['Banana', 'Apple', 'Beer', 'Water'];

this.form = new FormGroup({
  checkboxes: new FormGroup({ }),
});

this.items.forEach(item => {
  this.form.controls['checkboxes'].addControl(item, new FormControl(true));
});

Loop items instead of FormArray.

<form [formGroup]="form.controls['checkboxes']">
    <div *ngFor="let item of items">
        <input type="checkbox" [formControlName]="item">
        <span>{{ item }}</span>
    </div>
</form>

Plnkr: http://plnkr.co/edit/qHjpejOhSfw25YHhJNqV?p=preview

2
  • Ahhh perfect. Thank you very much! Commented Feb 28, 2017 at 14:53
  • damn, such a simple solution was breaking my head on it...thanks!
    – mtholen
    Commented Aug 16, 2022 at 3:33
2

This is another way to create dynamic checkboxes using formArray and update the formArray based on checkbox selection. For this have a extra selected property for each dynamic list

component.html

<div *ngFor="let item of formArray.controls;" [formGroup]="item">
    <mat-checkbox [formControl]="item.get('selected')">
          {{item.get("name")?.value}}
    </mat-checkbox>
</div>

component.ts

"items": [
{
  "name": "Banana",
  "selected": true
},
{
  "name": "Apple",
  "selected": false
}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.