I have a form here:
form = this.fb.group({
username: new FormControl('', Validators.required),
password: new FormControl('', [
Validators.required,
Validators.minLength(10),
]),
confirmPassword: new FormControl('', Validators.required),
firstname: new FormControl('', Validators.required),
lastname: new FormControl('', Validators.required),
email: new FormControl(null, [Validators.required, Validators.email]),
phone: new FormControl(null, [
Validators.required,
Validators.pattern(
'^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$'
),
]),
roles: this.fb.array([]),
});
Please notice that only the roles is a formArray object, now I have a function that related to multipuly checkboxs, I want to store the value that what user have selected/checked:
here is the function :
onChange(event: any) {
console.log(event);
console.log(this.form);
const roleFormArray = <FormArray>this.form.value.roles;
if (event.target.checked) {
roleFormArray.push(event.target.defaultValue);
} else {
let index = roleFormArray.value.findIndex(
(x) => x.value == event.target.defaultValue
);
roleFormArray.removeAt(index);
}
}
On HTML, it is simple like this:
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
value="User"
id="userCheck"
(change)="onChange($event)"
/>
<label class="form-check-label" for="userCheck"> User </label>
<br />
<input
class="form-check-input"
type="checkbox"
value="Manager"
id="managerCheck"
onchange="onChange($event)"
/>
<label class="form-check-label" for="managerCheck"> Manager </label>
</div>
So bacially I wish that my code runs, if user check the role - User, then it should add into array "User" (this is successfully) , but when the User de-selected the User checkbox, it throw the error - Cannot read property 'findIndex' of undefined
Don't know why the findIndex cannot provide me the index from FormArray. Any suggestions? Thanks!!