Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - restore previous value on cancel in two-way data binding

In two-way data binding what if user decides to cancel the current edits? How can this be achieved in angular 2?

Consider the following piece of code:

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: `Name: {{ name  }}<br>
    <input *ngIf='editMode' type="text" [(ngModel)]='name' /><br>
    <button *ngIf='!editMode' (click)='editMode = !editMode' >Edit</button>
    <button *ngIf='editMode' (click)='editMode = !editMode' >Save</button><br>
    <button *ngIf='editMode' (click)='editMode = !editMode' >Cancel</button>`
})
export class AppComponent {
  public name = 'Essa';
  public editMode false;
}

I want the old value to be restored when the user presses the cancel button.

Here is the plunker as an example.

like image 867
Eesa Avatar asked Mar 26 '16 16:03

Eesa


1 Answers

I don't think there is some direct support for this. Just store the value and restore it on cancel

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: `Name: {{ name  }}<br>
    <input *ngIf='editMode' type="text" [(ngModel)]='name' /><br>
    <button *ngIf='!editMode' (click)='startEdit()' >Edit</button>
    <button *ngIf='editMode' (click)='save()' >Save</button><br>
    <button *ngIf='editMode' (click)='cancel()' >Cancel</button>`
})
export class AppComponent {
  public name = 'Essa';
  public editMode false;
  startEdit() {
    this.oldName = this.name;
    this.editMode = !this.editMode;
  }
  save() {
    this.editMode = !this.editMode;
  }
  cancel() {
    this.editMode = !this.editMode;
    this.name = this.oldName;
  }
}

The methods startEdit, save and cancel don't need to be added explicitely to the component. Bindings can contain more than one statement separated by ; but I like this approach better if it's more than one statement.

Plunker

like image 154
Günter Zöchbauer Avatar answered Oct 20 '22 12:10

Günter Zöchbauer