Angular2 Form Builder, store array of values

1.5k views Asked by At

I'm using Angular 2 Reactive Form builder like this:

<div class="questionSection">
    <b class="questionTitle">Remove records that don't have:</b>
    <div class="horizontalOptions">
        <label 
        class="horizontalOption"
        *ngFor="let choice of excludeRecords"
        >
            <input type="checkbox"
            [value]="choice.value"
            formControlName="excludedRecords"
            >
            {{choice.label}}
        </label>
    </div>
</div>

I want the excludedRecords value to be an array, this is the variable that's generating the HTML:

excludeRecords = [
        {label: 'Full Mailing Address', value:'fullMailing', checked:false},
        {label: 'Full Office Address', value:'fullOffice', checked:false},
        {label: 'Email Address', value:'emailAddress', checked:false},
        {label: 'Phone #', value:'phoneNum', checked: false},
    ];

And this is how i'm generating the initial form selections:

constructor(private formBuilder: FormBuilder) {
    this.initialValues = {
        mainChoice: 'entireUSA',
        excludedRecords: [],
        stateChoice: 'all',
        includedStates: [],
        specialtyChoice: 'all',
        includedSpecialties: []
    }
    this.form = formBuilder.group(this.initialValues);
    this.formSelections = this.initialValues;

    this.form.valueChanges.subscribe(
        data => {
            console.log('form changed', data);
            this.formSelections = data;
        }
    );
}

Right now it just switches the value to true or false, but I want each checkbox inputs to output an array of values, is this possible with Angular2 Form Builder?

1

There are 1 answers

0
Jordan Lamour On

I found a solution. In my case I have multiple categories. Categories have an id, a name and a selected property for the form.

    <label *ngFor="let category of categories">
    {{category.name}}

    <input [checked]="book.category_ids.includes(category.id)"
           type="checkbox"
           id="{{category.id}}"
           value="{{category.name}}"
           formControlName="category_ids"
           (change)="updateCheckedOptions(category.id, $event)">
    </label>

Every time a checkbox is checked, I update the categories. At this time category_ids is set to true of false. Before submitting the form, I manually update the category_ids field with the selected values.