My problem is really simple: I have a list of checkboxes like this:
<div class="form-group"> <label for="options">Options :</label> <label *ngFor="#option of options" class="form-control"> <input type="checkbox" name="options" value="option" /> {{option}} </label> </div>
And I would like to send an array of the selected options, something like: [option1, option5, option8]
if options 1, 5 and 8 are selected. This array is part of a JSON that I would like to send via an HTTP PUT request.
Thanks for your help!
Here's a simple way using ngModel
(final Angular 2)
<!-- my.component.html --> <div class="form-group"> <label for="options">Options:</label> <div *ngFor="let option of options"> <label> <input type="checkbox" name="options" value="{{option.value}}" [(ngModel)]="option.checked"/> {{option.name}} </label> </div> </div>
// my.component.ts @Component({ moduleId:module.id, templateUrl:'my.component.html'}) export class MyComponent { options = [ {name:'OptionA', value:'1', checked:true}, {name:'OptionB', value:'2', checked:false}, {name:'OptionC', value:'3', checked:true} ] get selectedOptions() { // right now: ['1','3'] return this.options .filter(opt => opt.checked) .map(opt => opt.value) } }
I have find a solution thanks to Gunter! Here is my whole code if it could help anyone:
<div class="form-group"> <label for="options">Options :</label> <div *ngFor="#option of options; #i = index"> <label> <input type="checkbox" name="options" value="{{option}}" [checked]="options.indexOf(option) >= 0" (change)="updateCheckedOptions(option, $event)"/> {{option}} </label> </div> </div>
Here are the 3 objects I'm using:
options = ['OptionA', 'OptionB', 'OptionC']; optionsMap = { OptionA: false, OptionB: false, OptionC: false, }; optionsChecked = [];
And there are 3 useful methods:
1. To initiate optionsMap
:
initOptionsMap() { for (var x = 0; x<this.order.options.length; x++) { this.optionsMap[this.options[x]] = true; } }
2. to update the optionsMap
:
updateCheckedOptions(option, event) { this.optionsMap[option] = event.target.checked; }
3. to convert optionsMap
into optionsChecked
and store it in options
before sending the POST request:
updateOptions() { for(var x in this.optionsMap) { if(this.optionsMap[x]) { this.optionsChecked.push(x); } } this.options = this.optionsChecked; this.optionsChecked = []; }
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