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. I tried to push to this.userForm.value.rolesToAdd but it was returning as undefined.
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
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
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.