【发布时间】:2020-09-22 08:21:57
【问题描述】:
我在 Angular 对话框中传递数据,但与此同时,当我在对话框中编辑某些内容时,即使我没有保存它们,它也会覆盖数据。 例如,我有一个对象,然后单击 ot 编辑它。 它会打开一个包含此对象的所有数据的 Angular 对话框。
是否只能在单击保存按钮时更改数据。
我听说 Object.assign 它可能很有用,但不知道如何使用它。
我尝试使用Object.assign,但没有成功。
为什么不起作用我认为 this.data 包含另一个数据作为 this.data.education。
请参阅下面的代码
这是我的对话框代码。
constructor(@Inject(MAT_DIALOG_DATA) public data: EditEducation,
private dialogRef: MatDialogRef<EducationDialogComponent>,
public dataService: ModelDataService) { }
ngOnInit(): void {
if (!this.data.edit) {
this.data.education = {} as SubCategory;
} else {
({education: this.data.education} = Object.assign({}, this.data));
}
}
这就是我打开对话框的方式。
<ul>
<li class="fa fa-pencil addIconTop" (click)="editEducation({edit: true, education: subCategory, model: model})"></li>
<button (click)="addEducation({edit: false, model: model})" class="btn"><i class="fa fa-plus addIconBottom"></i></button>
<button [disabled]="education.subCategories.length === 1" (click)="deleteSubCategory(i)" class="btn"><i class="fa fa-trash deleteIconRight"></i></button>
<li class="fa fa-arrow-down moveIconDown"></li>
<li class="fa fa-arrow-up moveIconTop"></li>
</ul>
public editData(data: EditEducation) {
this.dialog.open(DataDialogComponent, {
data,
});
}
public addData(data: EditEducation) {
this.dialog.open(DataDialogComponent, {
data,
});
}
这是一个界面,看是否是一个新的对象或需要编辑。
export interface EditEducation {
education?: SubCategory;
edit?: boolean;
model?: Model;
}
这是Education的界面
export interface Education {
subCategories: EducationSubCategory[];
}
export interface EducationSubCategory {
name: string;
startDate: number;
endDate: number;
graduation: string;
title?: string;
description: string;
}
【问题讨论】:
-
是的。在这里创建副本是个好主意。如果您只需要浅拷贝,
this.data = Object.assign({}, data);或this.data = {...data};都是可靠的选择。如果您有嵌套的数组或对象,则需要递归复制。如果需要,请确保打开对话框的代码在保存后可以访问更新的值。 -
我试过了,但是没有用。我尝试过这样的事情。
({education: this.data.education} = Object.assign({}, this.data)); -
它“没用”不是我能帮忙的
-
@AluanHaddad 我编辑了我的评论,它再次覆盖它。是否需要在对话框组件或父组件中进行复制?
-
你可以在任何一个地方做。如果在对话框中,请在构造函数中执行,在其中注入值。
标签: javascript angular typescript