Angular patchValue()复选框

时间:2018-03-13 05:08:58

标签: angular

我正在构建一个包含三个复选框的表单:

<div class="col-md-12">
    <label for="role">{{ 'USERS.ROLE' | translate }}:</label>
    <ul class="nav mb-3">
        <li class="nav-item mr-2">
            <div class="form-group">
                <div class="form-check">
                    <label class="form-check-label" for="">
                    <input type="checkbox" class="form-check-input" (change)="roles($event, 1)">
                        {{ 'CODE_TABLE.USER_ROLE.1' | translate }}
                    </label>
                </div>
            </div>
        </li>
        <li class="nav-item mr-2">
            <div class="form-group">
                <div class="form-check">
                    <label class="form-check-label" for="">
                    <input type="checkbox" class="form-check-input" (change)="roles($event, 2)">
                        {{ 'CODE_TABLE.USER_ROLE.2' | translate }}
                    </label>
                </div>
            </div>
        </li>
        <li class="nav-item mr-2">
            <div class="form-group">
                <div class="form-check">
                    <label class="form-check-label" for="">
                    <input type="checkbox" class="form-check-input" (change)="roles($event, 3)">
                        {{ 'CODE_TABLE.USER_ROLE.3' | translate }}
                    </label>
                </div>
            </div>
        </li>
    </ul>
</div>

然后在我的组件中我需要在单击复选框时构建添加到数组,但此patchValue()似乎只修改该值。我试图推送到.userForm.value.rolesToAdd,但它返回未定义。

this.userForm = this.fb.group({
    accountsToAdd: [],
    accountsToDelete: [],
    email: '',
    name: '',
    rolesToAdd: [],
    rolesToDelete: [],
    userId: null,
});

roles(event, val) {
    if (event.target.checked) {
        this.userForm.patchValue({
            rolesToAdd: val
        });
    }
    console.log(this.userForm.value);
}

1 个答案:

答案 0 :(得分:1)

您需要为多个值设置FormArray

import { ..., FormArray } from '@angular/forms';


this.userForm = this.fb.group({
    accountsToAdd: [],
    accountsToDelete: [],
    email: '',
    name: '',
    rolesToAdd: new FormArray([]),
    rolesToDelete: [],
    userId: null,
});

和像这样的补丁值

(<FormArray>this.userForm.get('rolesToAdd')).push(
new FormGroup( {
   'role': val
})