Angular 2 - Error: No provider for FormControl

crossRT picture crossRT · May 13, 2017 · Viewed 12.3k times · Source

I writing a library for the community, which needs access to the form control and listens on the value changed.

Here's how I did previously when using angular 2.3 and 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();
        });
    }
}

But this code is not working anymore after upgrade to angular 4.1. Here's the error that I get: ERROR Error: Uncaught (in promise): Error: No provider for NgControl!

Any suggestion or idea for me to listen on the value changed in the directive?

UPDATE 1: here's my 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]
        };
    }
}

Answer

crossRT picture crossRT · May 14, 2017

This problem happens when the input is not a form control, due to I didn't provide a name attribute for the input. not related to Angular version problem.