Angular2 Form Builder,存储值数组

时间:2017-01-05 02:02:16

标签: angular angular2-formbuilder

我正在使用Angular 2 Reactive Form构建器,如下所示:

<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>

我希望excludedRecords值为数组,这是生成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},
    ];

这就是我如何生成初始表单选择:

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;
        }
    );
}

现在它只是将值切换为true或false,但我希望每个复选框输入都输出一个值数组,这是否可以使用Angular2 Form Builder?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。就我而言,我有多个类别。类别具有表单的id,名称和选定属性。

    <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>

每次选中复选框时,我都会更新类别。此时,category_ids设置为true为false。在提交表单之前,我手动使用所选值更新category_ids字段。