Angular2 - 单击按钮更新模型 [英] Angular2 - Update model on button click

查看:29
本文介绍了Angular2 - 单击按钮更新模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 angular2 ngModel 进行双向数据绑定时:

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

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

有没有办法只在点击按钮后更新模型?或者能够取消用户对输入控件所做的更改?我知道另一种方法,我们可以在它的 []() 中拆分 [(ngModel)] 并且只更新输入在模糊或按下 Enter 键时等 - 但这不是我想要的.

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

推荐答案

你可以这样做,

演示: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);
  }
}

这篇关于Angular2 - 单击按钮更新模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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