重置表单后,有没有办法监听指令中的事件?

时间:2019-01-08 23:32:27

标签: angular typescript

通过使用事件或生命周期钩子重设表单后,是否可以从指令收听

我有这样的表格:

<form [formGroup]="myForm" (ngSubmit)="onFormSubmit($event)">
  <input type="text" formControlName="firstName" myDirective/>
  <button id="btnClear" (click)="onReset($event)">Clear</button>
</form>

我的组件

   @Component({
     selector: 'app-form',
     templateUrl: './app-form.component.html',
     styleUrls: ['./app-form.component.scss']
   })
   export class AppSearchFormComponent implements OnInit {

   myForm: FormGroup;

   constructor(private _fb: FormBuilder, private store: Store<any>) { }

   ngOnInit() {
   this.createForm();
   }

   createForm(){
       this.myForm = this._fb.group({
       'firstName': ['', [Validators.minLength(2)]]
    });
   }

 onReset(evt) {
  this.myForm.reset();
  }
 }

我的自定义指令:

@Directive({
  selector: '[myDirective]'
})
export class CustomDirective {

   constructor(private el: ElementRef, private control : NgControl) { }

     @HostListener('someEvent',['$event'])
      onkeyup(event:any){

       console.log('Yes Form has been reset!); // I want to display this message
     }
  }

1 个答案:

答案 0 :(得分:1)

使用 NgControl

  

所有基于FormControl的控制指令扩展的基类。它   将FormControl对象绑定到DOM元素。

将NgControl插入指令构造函数中,然后使用valuechanges方法订阅更改

import { Directive} from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
  selector: '[reset]',
})
export class ResetDirective {
  constructor(private ngControl: NgControl) { }
  ngOnInit() {
    const reset$ = this.ngControl.control.valueChanges;
    reset$.subscribe((e) => {
      if (e === null) {
        console.log('Yes Form has been reset!');
      }
    });
  }
}

示例:https://stackblitz.com/edit/reset-directive