在我的角度项目中,有一个显示在表中的数据库中的数组。无论何时单击某一行,都会使用ngSwitch
从显示组件更改为编辑组件。在编辑组件中,我想实现一个按钮,该按钮将取消对该行所做的任何更改,并将行中的数据设置回原来的状态。我该怎么做呢?
答案 0 :(得分:1)
切换到“编辑模式”时,将数据复制到另一个数据对象/数组中并显示该数据。保存时,执行您通常执行的操作并更新主数据集;取消时,只需清除已编辑的数据对象。
即
myDataCollection: myDataObject[];
myEditedData: myDataObject;
edit(id: string): void {
const data = his.myDataCollection.find(a => a.id === id);
if(!data) return; // make sure the data / ID is valid
this.myEditedData = new myDataObject(data); // copy constructor,
// or use a clone() method or something so it's
// not a reference to the same object as the original
// switch to edit mode in template
// (this can be done by checking "myEditedData?.id === data.id" in a
// *ngFor="let data of myDataCollection")
}
cancelEditing(): void {
this.myEditedData = null;
// switch from edit mode in template
}
saveEdits(): void {
// | where "setTo" is you function to
// v copy another object's properties
this.myDataCollection.find(a => a.id === id).setTo(this.myEditedData);
this.myEditedData = null; // or publish your edits back to the db,
// then set to null.
}
虽然如果您使用单独的组件进行“显示”和“编辑”,那么请将编辑组件设为myData
和myEditedData
,然后将myDataCollection.find(...)
语句切换为仅参考myData
。您还必须有一个“已更改”的事件或其他东西传回父组件以使用新对象更新其数据集合。