簡體   English   中英

Angular - 當它們在 component.ts 文件中啟動時,如何從指令內部檢測表單事件?

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

如果我有一個帶有表單輸入的組件,並且我想將 OnInit 塊中的兩個語句檢測為指令中的事件,那么正確的方法是什么? 我在“輸入”和“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);
    }
}

StackBlitz 中最小復制(觀看控制台)

您必須實現AfterViewInit而不是OnInit 原因是在生命周期的這一點上,您的指令已被初始化並通過@HostListener裝飾器訂閱了ngModelChange事件。

另請參閱Angular Life Cycle Hooks 文檔

閃電戰


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'
    })
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM