[英]Angular patchValue() checkboxes
I am building a form that has three checkboxes: 我正在构建具有三个复选框的表单:
<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>
and then in my component i need to build add to an array when the checkbox is clicked, but this patchValue() seems to only modify the value. 然后在我的组件中,当单击复选框时,我需要构建添加到数组的数组,但是此patchValue()似乎只能修改该值。 I tried to push to this.userForm.value.rolesToAdd but it was returning as undefined.
我试图推送到this.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);
}
You need to have a FormArray for multiple values 您需要具有一个FormArray用于多个值
import { ..., FormArray } from '@angular/forms';
this.userForm = this.fb.group({
accountsToAdd: [],
accountsToDelete: [],
email: '',
name: '',
rolesToAdd: new FormArray([]),
rolesToDelete: [],
userId: null,
});
and patch value like this 和补丁值是这样的
(<FormArray>this.userForm.get('rolesToAdd')).push(
new FormGroup( {
'role': val
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.