Search code examples
angularangular-ngmodel

Angular2 - Update model on button click


When using the angular2 ngModel for two-way data binding:

<input [(ngModel)]="heroName">

Is there a way to only update the model once a button is clicked? Or be able to cancel the changes that the user made to the input control? I am aware of the other approach where we can split the [(ngModel)] in its [] and () and only update the input on blur or when the Enter key is pressed etc - but this is not what I want.

I need this behavious because, the user must be able to cancel the changes. Thanks


Solution

  • You can do following for that,

    DEMO : http://plnkr.co/edit/OW61kGGcxV5MuRlY8VO4?p=preview

    {{heroName}}<br>
    <input [ngModel]="heroName" #change> <br>
    <br>
    <button (click)="update(change.value)">Update Model</button>
    

    export class App {
      heroName="Angular2";
      update(value){
        console.log('value before button click' + this.heroName);
        this.heroName=value;
        console.log('value after button click' + this.heroName);
      }
    }