Skip to content

Instantly share code, notes, and snippets.

@kshep92
Created August 29, 2016 14:26
Show Gist options
  • Save kshep92/794ae47740af690a1a0d250dd8787e49 to your computer and use it in GitHub Desktop.
Save kshep92/794ae47740af690a1a0d250dd8787e49 to your computer and use it in GitHub Desktop.
How to handle checkbox group in Angular 2 RC5
<form [formGroup]="subscriptionForm">
<div>
<label>Frequency</label>
<p *ngFor="let schedule of viewData.schedules">
<input type="checkbox"
[checked]="subscription.schedules.includes(schedule)"
(change)="changeSchedules(schedule)"> {{ schedule.display }}
</p>
</div>
</form>
//
viewData = {
subscriptions: [
{id: 'weekly', display: 'Weekly update'},
{id: 'monthly', display: Montly update'},
{id: 'quarterly', display: 'Quarterly update'}
]
}
// The order retrieved from the server
subscription = {
schedules: [{id: 'weekly', display: 'Weekly update'}],
}
//The FormGroup element
this.subscriptionForm = new FormGroup({
//Here I fill up a FormArray with some FormControls initialized to the
//currently selected schedules
schedules: new FormArray(this.subscription.schedules.map(schedule => new FormControl(schedule)), Validators.minLength(1))
});
//The method that manages adding and removing subscriptions from the user's selection
changeSchedules(schedule: any) {
var currentScheduleControls: FormArray = this.subscriptionForm.get('schedules') as FormArray;
var index = currentScheduleControls.value.indexOf(schedule);
if(index > -1) currentScheduleControls.removeAt(index) //If the user currently uses this schedule, remove it.
else currentScheduleControls.push(new FormControl(schedule)); //Otherwise add this schedule.
}
@ThomasBurleson
Copy link

When would you need to re-add during a (change) ChangeSchedules() event?

currentScheduleControls.push(new FormControl(schedule)); //Otherwise add this schedule.

The controls will only fire that event if present and then you would remove the control. Right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment