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
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.
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
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
}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With