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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With