gpt4 book ai didi

javascript - Angular2 - 选中 ngFor 和 react 形式中的复选框

转载 作者:行者123 更新时间:2023-12-03 02:52:15 25 4
gpt4 key购买 nike

我有一个从数据库返回的对象,该对象是名称及其 ID 的列表,以及它们是否被选择。

对象:

let data = [{
AttributeID: 1,
AttributeName: 'Something',
IsSelected: 'True'
},
{
AttributeID: 2,
AttributeName: 'Something Else',
IsSelected: 'False'
}]

HTML:

 <div *ngFor="let data of modalData.variableData">
<input type="checkbox" (change)="onAttributeCheckboxChange(data.AttributeID, $event.target.checked)" [checked]="(data.IsSelected == 'True' ? 1 : 0)"> {{data.AttributeName}}<br>
</div>

组件:

private settingsForm: FormGroup;

ngOnInit() {
this.settingsForm = this.fb.group({
attribute: this.fb.array([])
});
}


onAttributeCheckboxChange(attribute: number, isChecked: boolean) {
const attributeFormArray = <FormArray>this.settingsForm.controls.attribute;

if (isChecked) {
attributeFormArray.push(new FormControl(attribute));
} else {
let index = attributeFormArray.controls.findIndex(x => x.value == attribute)
attributeFormArray.removeAt(index);
}
}

我在这里做错了,因为虽然特定的框在我的用户界面上显示为checked,但当我提交表单时,数组返回为空。

onSave() {
console.log(this.settingsForm.value)
}

如何确保form知道最初选中了哪些复选框,而不仅仅是通过[checked]来选中元素本身?

最佳答案

您可以在 OnInit 上检查数据,并将检查的数据推送到表单数组,方法与在 onChange 上完成的方式相同:

export class App {
emails = [{email:"email1", isSelected: 'true'},{email:"email2", isSelected: 'false'},{email:"email3", isSelected: 'true'},{email:'email4', isSelected: 'false'}]
myForm: FormGroup;

constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
useremail: this.fb.array([])
});
}

ngOnInit() {
for(let item of this.emails){
if (item.isSelected === 'true'){
this.myForm.controls.useremail.push(new FormControl(item.email));
}
}
}

onChange(email:string, isChecked: boolean) {
const emailFormArray = <FormArray>this.myForm.controls.useremail;

if(isChecked) {
emailFormArray.push(new FormControl(email));
} else {
let index = emailFormArray.controls.findIndex(x => x.value == email)
emailFormArray.removeAt(index);
}
}

submitForm(event){
console.log(this.myForm.value);
}

}

你有一个工作plunkr here

关于javascript - Angular2 - 选中 ngFor 和 react 形式中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47800086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com