[angular] Can't bind to 'formGroup' since it isn't a known property of 'form'

THE SITUATION:

Please help! I am trying to make what should be a very simple form in my Angular2 app but no matter what it never works.

ANGULAR VERSION:

Angular 2.0.0 Rc5

THE ERROR:

Can't bind to 'formGroup' since it isn't a known property of 'form'

enter image description here

THE CODE:

The view:

<form [formGroup]="newTaskForm" (submit)="createNewTask()">
   <div class="form-group">
      <label for="name">Name</label>
      <input type="text" name="name" required>
   </div>
   <button type="submit" class="btn btn-default">Submit</button>
</form>

The controller:

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder }  from '@angular/forms';
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
import { Task } from './task';

@Component({
    selector: 'task-add',
    templateUrl: 'app/task-add.component.html'

})
export class TaskAddComponent {

    newTaskForm: FormGroup;

    constructor(fb: FormBuilder) 
    {
        this.newTaskForm = fb.group({
            name: ["", Validators.required]
        });
    }

    createNewTask()
    {
        console.log(this.newTaskForm.value)
    } 
}

The ngModule:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

import { routing }        from './app.routing';
import { AppComponent }  from './app.component';
import { TaskService } from './task.service'

@NgModule({
    imports: [ 
        BrowserModule,
        routing,
        FormsModule
    ],
    declarations: [ AppComponent ],
    providers: [
        TaskService
    ],
    bootstrap: [ AppComponent ]
})
export class AppModule { }

THE QUESTION:

Why am I getting that error?

Am I missing something?

This question is related to angular typescript angular2-forms

The answer is


I've been struggling with this error during the last 3 days. I added the ReactiveFormsModule and FormsModule as mentionned in the comments above in both of my modules but it had no effect until I reloaded my project with another "ng serve". I don't know why it didn't reload automatically but at least i'm glad it worked finally! Any explanation please?


if this is just a typescript error but everything on your form works,you may just have to restart your IDE


My solution was subtle and I didn't see it listed already.

I was using reactive forms in an Angular Materials Dialog component that wasn't declared in app.module.ts. The main component was declared in app.module.ts and would open the dialog component but the dialog component was not explicitly declared in app.module.ts.

I didn't have any problems using the dialog component normally except that the form threw this error whenever I opened the dialog.

Can't bind to 'formGroup' since it isn't a known property of 'form'.


Can't bind to 'formGroup' since it isn't a known property of 'form'

means that you try to bind a property using angular ([prop]) but angular cant find anything he knows for that element (in this case form).

this can happen by not using the right module (missing an import somewhere in the way) and sometimes just cause a typo like:

[formsGroup], with s after form


I had the same issue with Angular 7. Just import following in your app.module.ts file.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Then add FormsModule and ReactiveFormsModule in to your imports array.

imports: [
  FormsModule,
  ReactiveFormsModule
],

Don't be a dumb dumb like me. Was getting the same error as above, NONE of the options in this thread worked. Then I realized I capitalized 'F' in FormGroup. Doh!

Instead Of:

[FormGroup]="form"

Do:

[formGroup]="form"


Note : if you are working inside child module's component , then u just have to import ReactiveFormsModule in child module rather than parent app root module


Might help someone:

when you have a formGroup in a modal (entrycomponent), then you have to import ReactiveFormsModule also in the module where the modal is instantiated.


Import ReactiveFormsModule in the corresponded module


Keep in mind that if you have defined "Feature Modules", you'll need to import in the Feature Module, even if you already imported to the AppModule. From the Angular documentation:

Modules don't inherit access to the components, directives, or pipes that are declared in other modules. What AppModule imports is irrelevant to ContactModule and vice versa. Before ContactComponent can bind with [(ngModel)], its ContactModule must import FormsModule.

https://angular.io/docs/ts/latest/guide/ngmodule.html


You need to import the FormsModule, ReactiveFormsModule in this module as well as the top level.

If you used a reactiveForm in another module then you've to do also this step along with above step: import also reactiveFormsModule in that particular module.

For example:

imports: [
  BrowserModule,
  FormsModule,
  ReactiveFormsModule,
  AppRoutingModule,
  HttpClientModule,
  BrowserAnimationsModule
],

If you have this problem when you developing a component so you should add these two modules to your closest module :

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
   // other modules
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And if you are developing a test for your components so you should add this module to your test file like this:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ContactusComponent } from './contactus.component';
import { ReactiveFormsModule } from '@angular/forms';

describe('ContactusComponent', () => {
  let component: ContactusComponent;
  let fixture: ComponentFixture<ContactusComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ContactusComponent],
      imports:[
        ReactiveFormsModule
      ]

    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ContactusComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

I have encountered this error during unit testing of a component (only during testing, within application it worked normally). The solution is to import ReactiveFormsModule in .spec.ts file:

// Import module
import { ReactiveFormsModule } from '@angular/forms';

describe('MyComponent', () => {
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [MyComponent],
            imports: [ReactiveFormsModule],  // Also add it to 'imports' array
        })
        .compileComponents();
    }));
});

Once I added my module to the AppModule everything started working fine.


Import and register ReactiveFormsModule in your app.module.ts.

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
declarations: [
AppComponent,
HighlightDirective,
TestPipeComponent,
ExpoentialStrengthPipe

],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Make sure your spelling is correct in both .ts and .html file. xxx.ts

  profileForm = new FormGroup({
  firstName: new FormControl(''),
 lastName: new FormControl('')
 });

xxx.html file-

  <form [formGroup]="profileForm"> 
  <label>
  First Name:
   <input type="text" formControlName = "firstName">
  </label>

  <label>
  Last Name:
   <input type="text" formControlName = "lastName">
   </label>
   </form>

I was by mistake wrote [FormGroup] insted of [formGroup]. Check your spelling correctly in .html. It doesn't throw compile time error If anything wrong in .html file.


The error says that FormGroup is not recognized in this module. So You have to import these(below) modules in every module that uses FormGroup

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Then add FormsModule and ReactiveFormsModule into your Module's imports array.

imports: [
  FormsModule,
  ReactiveFormsModule
],

You may be thinking that I have already added it in AppModule and it should inherit from it? But it is not. because these modules are exporting required directives that are available only in importing modules. Read more here... https://angular.io/guide/sharing-ngmodules.

Other factors for these errors may be spell error like below...

[FormGroup]="form" Capital F instead of small f

[formsGroup]="form" Extra s after form


A LITTLE NOTE: Be careful about loaders and minimize (Rails env.):

After seeing this error and trying every solution out there, i realised there was something wrong with my html loader.

I've set my Rails environment up to import HTML paths for my components successfully with this loader (config/loaders/html.js.):

module.exports = {
  test: /\.html$/,
  use: [ {
    loader: 'html-loader?exportAsEs6Default',
    options: {
      minimize: true
    }
  }]
}

After some hours efforts and countless of ReactiveFormsModule imports i saw that my formGroup was small letters: formgroup.

This led me to the loader and the fact that it downcased my HTML on minimize.

After changing the options, everything worked as it should, and i could go back to crying again.

I know that this is not an answer to the question, but for future Rails visitors (and other with custom loaders) i think this could be helpfull.


Firstly, it is not related to Angular versions>2. Just import following in your app.module.ts file will fix the problems.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Then add FormsModule and ReactiveFormsModule in to your imports array.

imports: [
  FormsModule,
  ReactiveFormsModule
],

Note : You can also import ReactiveFormsModule to specific module instead to app.module.ts


The suggested answer did not work for me with Angular 4. Instead I had to use another way of attribute binding with the attr prefix:

<element [attr.attribute-to-bind]="someValue">

I had the same problem, make sure that if using submodules (for example, you not only have app.component.module.ts, but you have a separate component such as login.module.ts, that you include ReactiveFormsModule import in this login.module.ts import, for it to work. I don't even have to import ReactiveFormsModule in my app.component.module because I'm using submodules for everything.

login.module.ts:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { IonicModule } from '@ionic/angular';

import { LoginPageRoutingModule } from './login-routing.module';

import { LoginPage } from './login.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    IonicModule,
    LoginPageRoutingModule
  ],
  declarations: [LoginPage]
})
export class LoginPageModule {}

You can get this error message even if you have already imported FormsModule and ReactiveFormsModule. I moved a component (that uses the [formGroup] directive) from one project to another, but failed to add the component to the declarations array in the new module. That resulted in the Can't bind to 'formGroup' since it isn't a known property of 'form' error message.


I had the same issue and the problem was in fact only that I forgot to import and declare the component which holds the form in the module:

import { ContactFormComponent } from './contact-form/contact-form.component';

@NgModule({
    declarations: [..., ContactFormComponent, ...],
    imports: [CommonModule, HomeRoutingModule, SharedModule]
})
export class HomeModule {}

Simple solution :

step 1: import ReactiveFormModule

import {ReactiveFormsModule} from '@angular/forms';

step 2: add "ReactiveFormsModule" to import section

imports: [

    ReactiveFormsModule
  ]

Step 3: restart App and Done

Example :

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {ReactiveFormsModule} from '@angular/forms';
import { EscalationManagementRoutingModule } from './escalation-management-routing.module';
import { EscalationManagementRouteWrapperComponent } from './escalation-management-route-wrapper.component';


@NgModule({
  declarations: [EscalationManagementRouteWrapperComponent],
  imports: [
    CommonModule,
    EscalationManagementRoutingModule,
    ReactiveFormsModule
  ]
})
export class EscalationManagementModule { }

If you have to import two modules then add like this below

import {ReactiveFormsModule,FormsModule} from '@angular/forms';
@NgModule({
  declarations: [
    AppComponent,
    HomeComponentComponent,
    BlogComponentComponent,
    ContactComponentComponent,
    HeaderComponentComponent,
    FooterComponentComponent,
    RegisterComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routes,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Angular 4 in combination with feature modules (if you are for instance using a shared-module) requires you to also export the ReactiveFormsModule to work.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports:      [
    CommonModule,
    ReactiveFormsModule
  ],
  declarations: [],
  exports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ]
})
export class SharedModule { } 

Ok after some digging I found a solution for "Can't bind to 'formGroup' since it isn't a known property of 'form'."

For my case, I've been using multiple modules files, i added ReactiveFormsModule in app.module.ts

 import { FormsModule, ReactiveFormsModule } from '@angular/forms';`

@NgModule({
  declarations: [
    AppComponent,
  ]
  imports: [
    FormsModule,
    ReactiveFormsModule,
    AuthorModule,
],
...

But this wasn't working when I use a [formGroup] directive from a component added in another module, e.g. using [formGroup] in author.component.ts which is subscribed in author.module.ts file:

import { NgModule }       from '@angular/core';
import { CommonModule }   from '@angular/common';
import { AuthorComponent } from './author.component';

@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [
    AuthorComponent,
  ],
  providers: [...]
})

export class AuthorModule {}

I thought if i added ReactiveFormsModule in app.module.ts, by default ReactiveFormsModule would be inherited by all its children modules like author.module in this case... (wrong!). I needed to import ReactiveFormsModule in author.module.ts in order to make all directives to work:

...
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
...

@NgModule({
  imports: [
    ...,
    FormsModule,    //added here too
    ReactiveFormsModule //added here too
  ],
  declarations: [...],
  providers: [...]
})

export class AuthorModule {}

So, if you are using submodules, make sure to import ReactiveFormsModule in each submodule file. Hope this helps anyone.


For people strolling these threads about this error. In my case I had a shared module where I only exported the FormsModule and ReactiveFormsModule and forgot to import it. This caused a strange error that formgroups were not working in sub components. Hope this helps people scratching their heads.


I was coming across this error when trying to do e2e testing and it was driving me crazy that there were no answers to this.

IF YOU ARE DOING TESTING, find your *.specs.ts file and add :

import {ReactiveFormsModule, FormsModule} from '@angular/forms';

import { FormsModule, ReactiveFormsModule } from '@angular/forms'; and add it in imports array in the app-module.ts file.


using and import REACTIVE_FORM_DIRECTIVES:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent }  from './app.component';

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule
    ],
    declarations: [
        AppComponent
    ],
    bootstrap: [AppComponent]
})

export class AppModule { }

This problem occurs due to missing import of FormsModule,ReactiveFormsModule .I also came with same problem. My case was diff. as i was working with modules.So i missed above imports in my parent modules though i had imported it into child modules,it wasn't working.

Then i imported it into my parent modules as below, and it worked!

import { ReactiveFormsModule,FormsModule  } from '@angular/forms';
import { AlertModule } from 'ngx-bootstrap';

         @NgModule({
          imports: [
            CommonModule,
            FormsModule,
            ReactiveFormsModule,
    ],
      declarations: [MyComponent]
    })

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular2-forms

How can I manually set an Angular form field as invalid? Angular 2 Cannot find control with unspecified name attribute on formArrays Remove all items from a FormArray in Angular Angular ReactiveForms: Producing an array of checkbox values? How to make readonly all inputs in some div in Angular2? tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement" Min / Max Validator in Angular 2 Final TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm" Can't bind to 'formGroup' since it isn't a known property of 'form' ngModel cannot be used to register form controls with a parent formGroup directive