Created
August 29, 2016 14:26
-
-
Save kshep92/794ae47740af690a1a0d250dd8787e49 to your computer and use it in GitHub Desktop.
How to handle checkbox group in Angular 2 RC5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
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. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When would you need to re-add during a
(change)
ChangeSchedules() event?The controls will only fire that event if present and then you would remove the control. Right?