简体   繁体   中英

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

<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});
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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