您需要,在创建 formArray 时使用 this.data.selectedRow.fields 的值
buildTaskFields() {
const arr = this.allColumns.map(element => {
return this.fb.control(this.data.selectedRow.fields.indexOf(element)>=0);
});
return this.fb.array(arr);
}
查看 formArray 获取值,例如[真、假、假、真]
在 submitButton 中,我们使用 formArray 的值形成一个数组
onSave() {
const value=this.businessConfigForm.value.taskFieldsArray
this.data.selectedRow.fields=this.allColumns.filter((x,index)=>value[index])
this.dialogRef.close(null);
}
看到,当我们将行的对象本身作为数据传递时,我们可以在对话框组件中进行更改,并且我们不需要管理检查的“更改事件”
你的forked stackblitz
注意:您可以在this SO 中看到另一种管理复选框列表的方法,在这种情况下您不需要创建 formArray,只需使用变量array=[...this.data.selectedRow.fields](您需要复制)
更新如果我们想添加新功能,
首先是allColumns属于主组件,所以我们需要在data中传入这个数组,所以要编辑
this.dialog.open(AddConfigComponent, {
const selectedRow = evt.data;
data: {
data: selectedRow,
features:allColumns
}
在构造函数中
if (data) {
this.data = data.data;
this.allColumns=data.features;
}
好吧,现在再次添加一个新特征,当我们传递数组本身时,我们可以在保存中使用
this.data.push("another characteristic")
this.dialogRef.close(null);
更新 2 如果我们的特征是对象类型 {name:...} 而不仅仅是字符串,我们需要更改一些保存和 buildEditTaskFields
buildEditTaskFields() {
const arr = this.allColumns.map(element => {
//value becomes true if exist and object with name equal to the element
//see how we use find
const value=this.data.fields.find(f=>f.name==element)!=null;
return this.fb.control(value);
});
return this.fb.array(arr);
}
在保存中,过滤数组AllColumns后,我们将字符串数组“映射”到对象数组,有些像
onSave() {
const value = this.businessConfigForm.value.taskFieldsArray;
//the filter makes, e.g. the result is ["engine", "body-material"]
this.data.fields = this.allColumns.filter(
(x, index) => value[index]
//the map becomes to [{name:"engine"},{name:"body-material"}]
).map(x=>({name:x}));
this.dialogRef.close(null);
}