[英]Angular4: Recovering one-way data binding value on input after resetting the form
我有一个类似(简化版)的表格:
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
<!-- other inputs without data binding -->
<input
type="text"
id="item-input"
[ngModel]="myService.getCurrentItem().name"
name="item"
#item="ngModel">
<!-- other inputs without data binding -->
<button
(click)="onClearForm(f)">
New
</button>
</form>
并在组件上:
...
onClearForm(form: NgForm){
form.reset();
}
...
因此,在重置表单后,有效地清除了输入。 重置后如何从数据绑定中取回值?
您难道不就在重置表单之前获取值了吗...?
@ViewChild('item') item: string;
lastItem: string;
onClearForm(form: NgForm){
this.lastItem = this.item;
form.reset();
}
有两件事:我不会将函数调用数据绑定到表单控件。 Angular最终在幕后不断称呼这些人。 它可能会变得很丑陋,而且性能不佳。
仅通过双向数据绑定它可能更好。 这就是您对导出的item
模板变量所做的事情,但是更加简洁:
<input
type="text"
id="item-input"
[(ngModel)]="myItem"
name="item">
在组件中:
export class SomeComponent({
myItem: string = ''; // or whatever default value you want
constructor(public myService: MyService) {
this.myItem = myService.getCurrentItem().name;
}
onClearForm(form: NgForm){
let theValue = this.myItem;
form.reset();
console.log(`I still have myItem!: ${theValue});
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.