【发布时间】:2021-09-25 17:59:00
【问题描述】:
我这里有一个表格:
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([]),
});
请注意,只有角色是 formArray 对象, 现在我有一个与多复选框相关的功能,我想存储用户选择/检查的值:
这里是函数:
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);
}
}
在 HTML 上,很简单:
<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>
所以基本上我希望我的代码运行,如果用户检查角色 - 用户,那么它应该添加到数组“用户”(这是成功的),但是当用户取消选择用户复选框时,它抛出错误 - 无法读取未定义的属性“findIndex”
不知道为什么 findIndex 不能提供来自 FormArray 的索引。 有什么建议?谢谢!!
【问题讨论】:
-
我想下面的答案对你有帮助 let index = this.roleFormArray.findIndex(x => { if(x.value == event.target.defaultValue){ return x; } }) ; this.roleFormArray.splice(index , 1);
标签: angular formarray form-control