[英]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.