如何解决在 Angular 中,如何从 FormArray 对象获取索引?
我这里有一个表格:
form = this.fb.group({
username: new FormControl('',Validators.required),password: new FormControl('',[
Validators.required,Validators.minLength(10),]),confirmPassword: new FormControl('',firstname: new FormControl('',lastname: new FormControl('',email: new FormControl(null,[Validators.required,Validators.email]),phone: new FormControl(null,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 的索引。 有什么建议么?谢谢!!
解决方法
您添加复选框值并从 formarray 中删除的方式是错误的。在选择时,您需要创建 formcontrol 并将其添加到 formarray 上。取消选择时,您需要从 formarray 中删除 formcontrol。
onChange(event: any) {
console.log(event);
console.log(this.form);
const roleFormArray = <FormArray>this.form.controls['roles']; // Corrected
if (event.target.checked) {
roleFormArray.push(this.fb.control(event.target.defaultValue)); // Push control not value.
} else {
let index = roleFormArray.controls.findIndex( // Find item from controls.
(x) => x.value == event.target.defaultValue
);
roleFormArray.removeAt(index);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。