Get back old value on cancel for input-field

2019-08-20 12:23发布

问题:

I have a rather simple two-way data-binding for an input field and would like to have the value the input field binds to return to what it previously was when a "cancel" button is clicked.

Code is currently like this:

html:

<div *ngIf="editModeToggle" class="five wide column left floated">
  <div class="edit-on">
    <input type="text" class="header" [(ngModel)]="item.name">
  </div>
</div>
<div *ngIf="!editModeToggle" class="five wide column left floated">
  <div class="header">{{item.name}}</div>
</div>

  <div *ngIf="editModeToggle" class="one wide column">
    <a (click)="saveChanges(item)"><i class="save icon"></i></a>
  </div>
  <div *ngIf="editModeToggle" class="one wide column">
    <a (click)="cancelEdit()"><i class="cancel icon"></i></a>
  </div>

  <div *ngIf="!editModeToggle" class="one wide column">
    <a (click)="edit(item)"><i class="edit icon"></i></a>
  </div>

ts:

  edit(item: any) {
    this.editModeToggle = true;
    this.oldItemData = this.item;
    console.log('------ edit activate -------')
    console.log('old item:', this.oldItemData.name);
    console.log('item:', this.item.name);
  }

  saveSbuChanges(item: any) {
    // some stuff happens
    this.editModeToggle = false;
    console.log('------ save -------')
    console.log('old item:', this.oldItemData.name);
    console.log('item:', this.item.name);
  }

  cancelEdit() {
    this.editModeToggle = false;
    this.item = this.oldItemData;
    console.log('------ cancel -------')
    console.log('old item:', this.oldItemData.name);
    console.log('item:', this.item.name);
  }

What I would expect is that item.name, initialized with "ABC" would return to ABC when I click cancle. Instead, this.oldItemData.name takes on the new value.

Console-log:

------ edit activate -------  
old item: ABC  
item: ABC  
------ cancel -------  
old item: ABCD  
item: ABCD

what am I missing/how can I hav cancel return the value to what it as when edit-mode was activated?

回答1:

this.oldItemData is a reference to this.item. It will always contain the updated value. What you need to do is to copy the object. Here is an example:

this.oldItemData = JSON.parse(JSON.stringify(this.item));