取消输入字段时取回旧值

时间:2017-07-31 12:41:37

标签: angular input data-binding

我对输入字段有一个相当简单的双向数据绑定,并希望输入字段绑定的值返回到先前取消"取消"单击按钮。

代码目前是这样的:

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);
  }

我期望的是item.name,初始化为&#34; ABC&#34;当我点击cancle时会返回ABC。相反,this.oldItemData.name采用新值。

控制台日志:

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

我缺少什么/如何取消将值恢复为编辑模式被激活时的值?

1 个答案:

答案 0 :(得分:0)

this.oldItemData是对this.item的引用。它将始终包含更新的值。您需要做的是复制对象。这是一个例子:

  

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