Angular - 当表单事件在 component.ts 文件中启动时,如何从指令内部检测表单事件?

Angular - How do I detect form events from inside a directive when they are initiated in component.ts file?

如果我有一个带有表单输入的组件,并且我想将 OnInit 块中的两个语句检测为指令中的事件,那么执行此操作的正确方法是什么?我在 'input' 和 'ngModelChange' 方面很幸运,但是 none 我尝试监听的事件是为了捕获模型驱动表单的 patchValue() 方法或模板驱动表单的直接赋值(尽管它反映在 DOM).

这是我的组件:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms' 

@Component({
  selector: 'my-app',
  template:
  `
  <h5>Model form input</h5>
  <form [formGroup]="inputForm">
    <input patchable-input formControlName="input" />
  </form>

  <h5>Template form input</h5>
  <input patchable-input [(ngModel)]="input" />
  `
})
export class AppComponent implements OnInit {
  inputForm = new FormGroup({
    input: new FormControl('')
  })

  input = '';

  ngOnInit() {
    this.inputForm.patchValue({
      input: 'testing patch'
    })

    this.input = 'testing override'
  }
}

这是我的指令:

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[patchable-input]'
})
export class PatchableInputDirective  {
  @HostListener('ngModelChange', ['$event']) ngOnChanges($event) {
        console.log($event);
    }
}

minimal reproduction in StackBlitz(观看控制台)

您必须实施 AfterViewInit 而不是 OnInit。这样做的原因是在生命周期的这一点上,您的指令已经初始化并通过 @HostListener 装饰器订阅了 ngModelChange 事件。

另见 Angular Life Cycle Hooks documentation

stackblitz


import { Component, AfterViewInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms' 

@Component({
  selector: 'my-app',
  template:
  `
  <h5>Model form input</h5>
  <form [formGroup]="inputForm">
    <input patchable-input formControlName="input" />
  </form>

  <h5>Template form input</h5>
  <input patchable-input [(ngModel)]="input" />
  `
})
export class AppComponent implements AfterViewInit {
  inputForm = new FormGroup({
    input: new FormControl('')
  })

  input = '';

  ngAfterViewInit() {
    this.inputForm.patchValue({
      input: 'testing patch'
    })
  }
}