在 Angular 中,我们可以使用 [(ngModel)] 指令来将表单数据绑定到组件中的属性。如果您想在用户更改表单中的数据时显示旧数据,可以尝试以下方法。
1.在组件中创建变量来存储旧数据:
export class MyComponent { oldData: any;
constructor() { // 初始化旧数据 this.oldData = {firstName: 'John', lastName: 'Doe'}; } }
2.在表单中使用 [(ngModel)] 指令绑定数据:
3.监听表单的 valueChanges 事件:
this.myForm.valueChanges.subscribe((newValue) => { // 存储旧数据 this.oldData = {...this.myData}; });
4.当用户更改表单数据时,使用旧数据更新表单:
resetForm() { // 恢复旧数据 this.myData = {...this.oldData}; }
使用上述方法,您可以在用户更改表单值时显示旧数据。请注意,此方法仅适用于单个表单控件的更改。如果您想监视整个表单的更改,可以使用 FormGroup 的 valueChanges 事件。