[英]Angular2 - Update model on button click
When using the angular2 ngModel for two-way data binding: 当使用angular2 ngModel进行双向数据绑定时:
<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. 我知道另一种方法,我们可以将[(ngModel)]
拆分为其[]
和()
并且仅在模糊或按Enter键等时更新输入-但这不是我想要的。
I need this behavious because, the user must be able to cancel the changes. 我需要这个行为,因为用户必须能够取消更改。 Thanks 谢谢
You can do following for that, 您可以这样做,
DEMO : http://plnkr.co/edit/OW61kGGcxV5MuRlY8VO4?p=preview 演示: 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 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 例如,请参阅plunker- http: //plnkr.co/edit/0QEubJDzlgs0CdnKrS8h?p=preview
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.