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

时间:2019-03-12 15:53:56

标签: javascript angular angular-reactive-forms angular-directive angular-forms

如果我有一个带有表单输入的组件,并且想将OnInit块中的两个语句检测为指令中的事件,那么执行此操作的正确方法是什么?我对'input'和'ngModelChange'感到很幸运,但是我没有尝试听的任何事件都可以捕捉到模型驱动表单的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(观看控制台)

1 个答案:

答案 0 :(得分:1)

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

另请参阅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'
    })
  }
}