Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 - FormArray with Checkboxes

Tags:

angular

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

like image 1000
user2622344 Avatar asked Feb 28 '17 13:02

user2622344


People also ask

How do I use a checkbox in reactive form?

You can use reactive form with checkbox in angular 10 application. In this example, i simply take website array variable with list of variable and display list of checkbox with website name. i also added on change event to get selected checkbox value for reactive form element.


2 Answers

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

like image 183
Jari Pekkala Avatar answered Nov 15 '22 02:11

Jari Pekkala


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
}]
like image 40
Naren Avatar answered Nov 15 '22 02:11

Naren