表格重置事件通知?

Notification upon Form Reset Event?

有没有办法在通过 formReset 方法重置表单时得到通知?

我有一个注入表单的指令,当提交表单或通过重置按钮重置时,我会收到通知,但我无法找到在 ngForm 上调用 formRest 时收到通知的方法。

@Directive({
  selector: '[appForm]'
})
export class FormDirective implements OnDestroy {
  private subscription: Subscription;

  constructor(form: NgForm) {
    this.subscription = form.ngSubmit.subscribe(() => {
      console.log('submitted');
    });
    form.onReset = () => {
      console.log('reset');
    };
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

使用类似

的指令
<form appForm #form="ngForm">
  <button type="submit">Submit</button>
  <button type="reset">Reset</button>
  <button type="button" (click)="form.resetForm()">Angular reset</button>
</form>

有没有办法通知我的指令 resetForm 方法已被调用?

StackBlitz 演示 https://stackblitz.com/edit/angular-adymlf?file=src/app/form.directive.ts

基于w3schools onReset event,"reset"事件仅在<input type="reset">时触发。这可能是浏览器的默认行为。

Angular 的 resetForm()reset() 实际上不会触发重置事件。它只是以编程方式 还原 表单的值。 resetForm() 允许您重置 angular 表单的提交状态,还可以通过传入如下对象来定义要重置的表单的初始值:resetForm({}).

这可以通过在您的属性指令中添加一个 @HostListener('reset') 来侦听重置事件来证明。当调用 form.resetForm()form.reset() 时(或者更确切地说,单击),根本不会触发重置事件。


在按钮的属性指令中监听点击

要解决这个问题,您只需使用 <button type="reset">?但是,如果它不适合您的用例,并且您需要使用 <button type="button"> 并仍然检测到重置事件,那么您可以添加另一个 @HostListener 来监听按钮输入类型的点击事件:

@HostListener('click', ['$event.target']) onFormClick(btn: HTMLButtonElement){
  // console.log(btn)
  if(btn.type == "button"){
    console.log("detected click event on 'Angular reset' button, triggering reset event!");
    this.form.onReset();
  }
}

检测 NgForm 的 resetForm() 何时被调用(编辑)


//to store original resetForm()
resetFormFunc;

constructor(private form: NgForm, private elRef: ElementRef) {

   ...

   this.resetFormFunc = form.resetForm; //assigning resetForm function to "store" it.

   //"Override" resetForm(), and call original resetForm() in the middle
   form.resetForm = () => {
     console.log("detected calling of resetForm()!");
     this.resetFormFunc.apply(form, arguments); //actually call form.resetForm()
     console.log("my additional code");
   }
}

点击"Angular Reset"时:

#2 Forked Stackblitz ⚡

希望对您有所帮助!