Search code examples
jsonformscheckboxangularangular2-forms

Angular 2: Get Values of Multiple Checked Checkboxes


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!


Solution

  • 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 = [];
    }