2

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

这是我之前使用 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]
        };
    }
}
4

2 回答 2

4

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

于 2017-05-14T09:22:00.007 回答
0

你能试试这个吗?

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

@NgModule({
    ...
    providers: [FormControlDirective, FormGroupDirective]
})
于 2017-05-13T15:58:58.010 回答