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

Sign up to request clarification or add additional context in comments.

2 Comments

Ahhh perfect. Thank you very much!
damn, such a simple solution was breaking my head on it...thanks!
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
}]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.