如果我有一个带有表单输入的组件,并且我想将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(看控制台)
你必须实现AfterViewInit
而不是OnInit
。原因是在生命周期的这一点上你的指令已被初始化并通过ngModelChange
装饰器订阅了@HostListener
事件。
另见Angular Life Cycle Hooks documentation。
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'
})
}
}