代码之家  ›  专栏  ›  技术社区  ›  HenryDev

当窗体被重置时,是否有方法监听来自指令的事件?

  •  0
  • HenryDev  · 技术社区  · 6 年前

    有办法去吗 从指令监听 当使用 事件或生命周期挂钩 ?

    我有这样的表格:

    <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 回复  |  直到 6 年前
        1
  •  1
  •   Chellappan வ    6 年前

    使用 NG-控件

    所有基于控件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