Angular2 - Update model on button click

。_饼干妹妹 提交于 2019-12-01 12:09:57

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

You can separate your "live" data from your "valid" data.

Try something like this:

<input [(ngModel)]="live.heroName">
<button (click)="save()">Save</button>
<button (click)="reset()">Reset</button>

And the controller:

live = { heroName: '', heroPower: '' };
valid = { heroName: '', heroPower: '' };

save() {
    this.valid = Object.assign({}, this.live);
}

reset() {
    this.live = Object.assign({}, this.valid);
}

You can create a new property for the form binded property.

Would look like this

<input [(ngModel)]="formHeroName" #change> <br>
{{selectedHeroName}}
<br>

Update Model Cancel

export class App implements OnInit {
selectedHeroName="Angular2";
formHeroName = "";

ngOnInit() {
  this.formHeroName = this.selectedHeroName;
}

update(){
  this.selectedHeroName= this.formHeroName;
}

cancel() {
  this.formHeroName = this.selectedHeroName;
}
}

See plunker for example - http://plnkr.co/edit/0QEubJDzlgs0CdnKrS8h?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!