简体   繁体   English

Angular4:重置表单后,在输入中恢复单向数据绑定值

[英]Angular4: Recovering one-way data binding value on input after resetting the form

I have a form like (simplified version): 我有一个类似(简化版)的表格:

<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>

and on the component: 并在组件上:

  ...

  onClearForm(form: NgForm){
    form.reset();
  }

  ...

So, after resetting the form, the input get effectively gets cleared. 因此,在重置表单后,有效地清除了输入。 How do I get back the value from the data binding just after resetting? 重置后如何从数据绑定中取回值?

Couldn't you just grab the value before resetting the form...? 您难道不就在重置表单之前获取值了吗...?

@ViewChild('item') item: string;

lastItem: string;

onClearForm(form: NgForm){
    this.lastItem = this.item;
    form.reset();
}

A couple things: I wouldn't data-bind a function call to a form control. 有两件事:我不会将函数调用数据绑定到表单控件。 Angular ends up calling these constantly behind the scenes; Angular最终在幕后不断称呼这些人。 it can get pretty ugly and it's not performant. 它可能会变得很丑陋,而且性能不佳。

It's probably better to just two-way data bind it; 仅通过双向数据绑定它可能更好。 that's kind of what you're doing with the exported item template variable, but much more cleanly: 这就是您对导出的item模板变量所做的事情,但是更加简洁:

<input
  type="text"
  id="item-input"
  [(ngModel)]="myItem"
  name="item">

in component: 在组件中:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM