FrancescoMussi
FrancescoMussi

Reputation: 21610

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

The situation

I am trying to make what should be a very simple form in my Angular application, but no matter what, it never works.

The 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?

Upvotes: 1376

Views: 1538570

Answers (30)

kasmi zoubeir
kasmi zoubeir

Reputation: 46

I did Import ReactiveFormsModule but still got the error. I found that in my case (I'm using lazy looding), the mistake was that instead of importing login.module in app-routing I imported login-routing.module.

I.e. instead of

{ 
    path: 'login',
    loadChildren: () => import('./public/login/login-routing.module').then(m => m.LoginRoutingModule)
  },

I had to use

{
    path: 'login',
    loadChildren: () => import('./public/login/login.module').then(m => m.LoginModule)
  },

Upvotes: 1

Mounir bkr
Mounir bkr

Reputation: 1625

  1. go to: app.module.ts
  2. imports:[ .... ReactiveFormsModule ]
  3. add this: import { ReactiveFormsModule } from '@angular/forms';
  4. it should look like that:

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

@NgModule({
  declarations: [
  
  ],
  imports: [
    
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Upvotes: 38

SELA
SELA

Reputation: 6793

You seem to be using FormsModule in your AppModule.ts file. This is compatible with the Template-driven forms In Angular.

But in your controller or component file, you are referencing Reactive-form controls In Angular by importing ReactiveFormsModule-based controls. Ex: FormGroup, FormControl, Validators, FormBuilder

You can simply fix the error by Importing both modules at your root AppModule.ts file like below:

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

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

export class AppModule { }

Note: This is actually a design decision that needs to be taken before developing your application if you are developing an enterprise application based on the complexity of the application forms.

Usually, if you compare template-driven forms and reactive-forms in Angular

template-driven approach :

  • asynchronous nature
  • most of the logic is driven by the template

reactive-forms driven approach :

  • synchronous nature
  • most of the logic resides mainly in the component

Upvotes: 1

Giovannisc
Giovannisc

Reputation: 37

I solved this problem, but my component was not being added to the module declarations. To resolve this, add your component to the declarations array in the app.module.ts file: [YourComponent]. Then everything will be okay.

Upvotes: 1

Hamdhan Azeez T
Hamdhan Azeez T

Reputation: 488

check whether the component uses forms group is added in the declarations of app module.ts

@NgModule({ declarations: ['your component name']})

Upvotes: 0

Bagadi Venkat Ramesh
Bagadi Venkat Ramesh

Reputation: 301

in case you are using standalone components, import ReactiveFormsModule in the same component.ts file and in the @Component decorator, add a property called imports and give it an array containing the ReactiveFormsModule as an element. Like so:

import { Component } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-signin',
  standalone: true,
  templateUrl: './signin.component.html',
  styleUrls: ['./signin.component.css'],
  imports: [ReactiveFormsModule]
})
export class SigninComponent {
  signinForm = new FormGroup({
    email: new FormControl(''),
    password: new FormControl('')
  });
  
}

Upvotes: 6

R. Salisbury
R. Salisbury

Reputation: 2006

I had this issue and neither the imports nor restarting ng serve were the problem. In my case, the problem was that I had copied some Angular 8 code into a new project, which used the FormBuilder class to build form groups.

However in newer Angular versions, FormBuilder is a typed class. Changing to UntypedFormBuilder got the app to compile successfully. Every component in the module was reporting errors with basic bindings, not only [formGroup] but also [routerLink] and [ngClass], but I only had to fix the FormBuilder type in a single component for all of those to go away.

Upvotes: 0

Srikrushna
Srikrushna

Reputation: 4945

Error ex:error NG8002: Can't bind to 'formGroup' since it isn't a known property of 'form'.

I am giving possible reasons and solutions if the solution works/useful please upvote and make a comment which solution worked for you

Scenario 1 and suggestion: if you have only one module or the error appears in app component

You have to import the FormsModule, ReactiveFormsModule in the module

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

imports: [
  FormsModule,
  ReactiveFormsModule,
],

Scenario 2 and suggestion: when your application contains multiple modules

Import FormsModule and reactiveFormsModule in that particular module/submodule i.e. nearest module

Scenario 3 and suggestion: If you imported FormModule and ReactiveFormModule correctly there might be another problem.

Maybe you didn't add your component to module declarations in the app module. So add your component to module declarations.

import { YourComponentName } from './example-file-path/your-component-name.component';

@NgModule({
  declarations: [
    YourComponentName
  ]
})

Scenario 4 and suggestion: If you added ReactiveFormsModule and FormsModule as mentioned in the above.

Try to reload the project (restart the IDE) and start your server once again with ng serve

.

Upvotes: 12

Mounir bkr
Mounir bkr

Reputation: 1625

add "ReactiveFormsModule" in your <componenet.module.ts> parent

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

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

    ]
})
export class InvoiceModule { }

Upvotes: 9

Ashutosh Jha
Ashutosh Jha

Reputation: 16337

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.

Upvotes: 189

Mohamed Mohsen
Mohamed Mohsen

Reputation: 187

For Angular 14 and who uses sub-modules with routing

My issue was related to using sub-modules with routing. To make it works, follow these three steps:

1- In app.module

imports: [
//other-modules
ReactiveFormsModule

]

2- In sub-module

imports: [
//other-modules
ReactiveFormsModule

]

3- In app-routing.module add the following routing (my module was named AuthModule)

{
path: 'signup',
component: SignUpComponent,
children: [
  {
    path: '',
    loadChildren: () =>
      import('./features/auth/auth.module').then((m) => m.AuthModule),
  },
]

},

Hope this help somebody someday!

Upvotes: 2

Ramil Mammadov
Ramil Mammadov

Reputation: 532

If you imported FormModule and ReactiveFormModule correctly there might be another problem. Maybe you didn't add your component to module declarations in the app module. So add your component to app.module.ts declarations:

@NgModule({
  declarations: [
    YourNewComponent
  ]
})

Upvotes: 4

Mahi Kumawat
Mahi Kumawat

Reputation: 61

You can import formModule and reactiveFormModule

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


@NgModule({
    declarations: [
        ContactComponent
    ],
    imports: [
        CommonModule,
        ContactRoutingModule,
        FormsModule,
        ReactiveFormsModule
    ]
})
export class ContactModule { }

Upvotes: 2

Sarthak Maheshwari
Sarthak Maheshwari

Reputation: 537

If,
Already Imported

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

in rootModule & customComponentModule & still getting the error

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

just,

Restart you Application server

this will solve the issue

Upvotes: 1

Viplav Soni
Viplav Soni

Reputation: 1727

Three main points we have to focus on if encountered such types of issues.

  1. Import ReactiveFormsModule, FormsModule in any shared or app module.
  2. If you created a shared module then import that into a module on which you are using the form group and
  3. check that component is in declarations: [ ProjectComponent ] like this.

Upvotes: 3

Leelavathi Ravindran
Leelavathi Ravindran

Reputation: 119

The ReactiveFormsModule and FormsModule import should be added in your custom component module and also its parent component from where it is getting called.

For example, I needed to add form for my filter component. So I should add this import in my filter module and its parent page (might be list) module from where this filter button gets clicked.

Upvotes: 6

Nanda Kishore Allu
Nanda Kishore Allu

Reputation: 554

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

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

Then add FormsModule and ReactiveFormsModule into your imports array.

imports: [
  FormsModule,
  ReactiveFormsModule
],

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

Upvotes: 21

NDavis
NDavis

Reputation: 1227

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'.

Upvotes: 0

Shashwat Gupta
Shashwat Gupta

Reputation: 5264

Simple solution:

Step 1: Import ReactiveFormModule

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

Step 2: Add "ReactiveFormsModule" to the import section

imports: [

    ReactiveFormsModule
  ]

Step 3: Restart the application 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 { }

Upvotes: 9

tonertop
tonertop

Reputation: 51

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

Upvotes: 4

Peter Edwards
Peter Edwards

Reputation: 116

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.

File 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 {}

Upvotes: 6

Avi E. Koenig
Avi E. Koenig

Reputation: 379

If this is just a TypeScript error but everything on your form works, you may just have to restart your IDE.

Upvotes: 5

Meghnath Das
Meghnath Das

Reputation: 155

Import ReactiveFormsModule in the corresponding module.

Upvotes: 5

Abhishek Singh
Abhishek Singh

Reputation: 1671

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 in Sharing modules.

Other factors for these errors may be be a spelling error like below...

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

[formsGroup]="form" Extra s after form

Upvotes: 29

flyer
flyer

Reputation: 1424

Don't be a dumb dumb like me. I was getting the same error as above, and none of the options in previous answers worked. Then I realized I capitalized 'F' in FormGroup. Doh!

Instead of:

[FormGroup]="form"

Do:

[formGroup]="form"

Upvotes: 9

Leandro
Leandro

Reputation: 1522

Say you have structured your app like below:

  • AnotherModule
    • <your_form>
  • AppModule

Import ReactiveFormsModule or FormsModule in AnotherModule based on your form type.

Make sure AnotherModule is imported in AppModule.

Upvotes: -1

Hamid
Hamid

Reputation: 908

If you have this problem when you are developing a component, 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();
  });
});

Upvotes: 7

mojtaba ramezani
mojtaba ramezani

Reputation: 1559

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 { }

Upvotes: 6

tek
tek

Reputation: 353

I did not see this particular failure mechanism described here or any reference to public-api.ts elsewhere within this issue, so adding it in case it helps someone else.

I have a component built using Reactive Forms inside a feature module. Following the guidance described in other answers, my module built without issue UNTIL I attempted to export the component via public-api.ts. At that point, I began to get the familiar error Can't bind to 'formGroup' since it isn't a known property of 'form', with no other indication what might be wrong.

This issue occurred for me at this point because I forgot to declare and export the component from the NgModule. Once I added it there, the module began to build again. So, three things to remember in the NgModule when attempting to export a Reactive Forms component:

import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { MyExportedComponent } from './components/my-exported.component';


@NgModule({
    declarations: [
        MyExportedComponent // this
  ],
    imports: [
        ReactiveFormsModule // this
    ], 
    exports: [
        MyExportedComponent // and this
    ],
    providers: [
        ]
})
export class MyModule { }

At which point, Angular will play nice with this line in public-api.ts:

export * from './lib/my-module/components/my-exported.component';

Upvotes: 1

Stefan Svrkota
Stefan Svrkota

Reputation: 50613

RC6/RC7/Final release FIX

To fix this error, you just need to import ReactiveFormsModule from @angular/forms in your module. Here's the example of a basic module with ReactiveFormsModule import:

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 { }

To explain further, formGroup is a selector for directive named FormGroupDirective that is a part of ReactiveFormsModule, hence the need to import it. It is used to bind an existing FormGroup to a DOM element. You can read more about it on Angular's official docs page.

RC5 FIX

You need to import { REACTIVE_FORM_DIRECTIVES } from '@angular/forms' in your controller and add it to directives in @Component. That will fix the problem.

After you fix that, you will probably get another error because you didn't add formControlName="name" to your input in form.

Upvotes: 2278

Related Questions