0

I have a list which contains dynamic number of checkbox's, each is having id attribute.

<li *ngFor='let i of someArray'>
<input type="checkbox" id={{i}}>
</li>

I can assign each input checkbox if they are known previously by [(ngModel)] to those many number of variables.

But how to attach dynamic number of checkbox's with variables while preserving the concept of Two-Way binding.

I am using @angular/core 2.4.10.

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
techcomp
  • 370
  • 3
  • 16

3 Answers3

1

You'd have to use FormArray for this.

import {FormGroup} from '@angular/forms';

constructor(private fb: FormBuilder) {}

public form: FormGroup = this.fb.group({
  checkboxes: this.fb.array([])
});

Then you can loop from the controls:

<li *ngFor='let control of form.checkboxes.controls; let i = index'>
  <input type="checkbox" id={{i}} [formControl]="control">
</li>

Then you can get the value by doing this.form.get('checkboxes').value.

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • There is one edit which I have done to make it work.
  • Since you are accessing checkboxes using index, my problem is still same-how to uncheck/check these checkboxes when some conditions satisfies in background? – techcomp Jul 17 '17 at 14:05
  • @techcomp You just grab the form control and call `control.setValue(false)`, where `control` is a variable which holds the control. – Chrillewoodz Jul 18 '17 at 06:45