在输入字段中取回取消时的旧值 [英] Get back old value on cancel for input-field

查看:47
本文介绍了在输入字段中取回取消时的旧值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于输入字段,我有一个非常简单的双向数据绑定,并且希望让输入字段绑定的值返回到单击取消按钮时的状态。

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.

代码当前如下所示:

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

我期望的是使用 ABC初始化的item.name单击cancle时返回ABC。而是使用this.oldItemData.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.

控制台日志:

------ 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?

推荐答案

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

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

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

这篇关于在输入字段中取回取消时的旧值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆