Angular 2 - 错误:没有FormControl的提供程序

时间:2017-05-13 04:56:20

标签: angular angular-directive angular-providers angular-validation

我为社区编写了一个库,需要访问表单控件并监听更改的值。

以下是使用角度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]
        };
    }
}

2 个答案:

答案 0 :(得分:2)

当输入不是表单控件时会发生此问题,因为我没有为输入提供name属性。 与Angular版本问题无关。

答案 1 :(得分:0)

你能试试吗?

import { ..., FormControlDirective, FormGroupDirective } from '@angular/forms';

@NgModule({
    ...
    providers: [FormControlDirective, FormGroupDirective]
})