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.

3 Answers 3

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.

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

2 Comments

There is one edit which I have done to make it work. <li *ngFor='let control of form.get("checkboxes").controls; let i = index'> <input type="checkbox" id={{i}} [formControl]="control"> </li> 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 You just grab the form control and call control.setValue(false), where control is a variable which holds the control.
1

Unlike @Chrillewoodz said, you're not forced to use the Form Array, although I recommend you to use it. Otherwise you can do

<li *ngFor='let box of someArray; let i = index'>
    <input type="checkbox" [id]="box" [(ngModel)]="someArray[i]">
</li>

2 Comments

Is there some way to not access it by index ?
No, it throws an error because Angular tries to access dynamically created variables. You need to use the index if you don't want to use formArray.
0

FormArray can be used when you don’t know how many controls will be present or when you have dynamic elements in form.

FormArray is well explained in this stackoverflow answer

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.