我为社区编写了一个库,它需要访问表单控件并监听更改的值。
这是我之前使用 Angular 2.3 和 4.0 时的做法。
export class ValidationMessageDirective implements OnInit {
@Input('validationMessage') customMessage: string;
constructor(private el: ElementRef, private formControl: NgControl, private validationMessageService: ValidationMessageService) {
this.target = $(el.nativeElement);
this.formGroup = this.target.closest('.form-group');
this.formControl.valueChanges.subscribe((newValue) => {
this.checkValidation();
});
}
}
但是升级到 Angular 4.1 后,此代码不再起作用。这是我得到的错误:
ERROR Error: Uncaught (in promise): Error: No provider for NgControl!
有什么建议或想法让我听取指令中更改的值吗?
更新 1:
这是我的index.ts
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ValidationMessageDirective } from './src/ng2-validation-message.directive';
import { ValidationMessageService } from './src/ng2-validation-message.service';
export * from './src/ng2-validation-message.directive';
export * from './src/ng2-validation-message.service';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
declarations: [
ValidationMessageDirective
],
exports: [
ValidationMessageDirective
],
})
export class Ng2ValidationMessage {
static forRoot(): ModuleWithProviders {
return {
ngModule: Ng2ValidationMessage,
providers: [ValidationMessageService]
};
}
}