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

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

如果我有一个带有表单输入的组件,并且我想将 OnInit block 中的两个语句检测为指令中的事件,那么正确的方法是什么?我在“输入”和“ngModelChange”方面很幸运,但我尝试收听的所有事件都没有捕获模型驱动表单的 patchValue() 方法或模板驱动表单的直接分配(即使它反射(reflect)在 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'
    })
  }
}

关于javascript - Angular - 当表单事件在 component.ts 文件中启动时,如何从指令内部检测表单事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55125737/

相关文章:

javascript - ngAnimate 不再工作了吗?

使用 routerLink 的 Angular Mat-Tab-Group 导航

javascript - 验证并显示表单数组 Angular 中特定表单 Controller 的错误消息

javascript - JSON 次要数据移除器

javascript - Angularjs 读取模板中对象的值

javascript - 使用 Javascript 或 jQuery 将元素写入子 iframe

javascript - ionic 2 : hide and display div with ngClass

angular - md-list-icon 或 md-button 右对齐? (棱 Angular Material 2)

javascript - 带有 Angular 6(Angular Material)单选按钮和 *ngIf 的显示元素

angular - 类型错误 : Converting circular structure to JSON property 'name' closes the circle