Total Pageviews

Thursday 20 June 2019

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


If there are multiple module files in application then only adding ReactiveFormsModule in app.module.ts is not enough.



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

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



This will not work, when I use a [formGroup] directive from a component added in another module, e.g. using [formGroup] in register.component.ts which is subscribed in register.module.ts file:

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

@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [
    RegisterComponent,
  ],
  providers: [...]
})
export class RegisterModule {}



By default ReactiveFormsModule would be inherited by all its children modules like register.module but this is not true in this case. We need to import ReactiveFormsModule in register.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 RegisterModule {}



So, the conclusion is if there are submodules in application, then make sure to import ReactiveFormsModule in each submodule file.

3 comments:

Microsoft Logo using flexbox and Reactjs

 <!DOCTYPE html> <html> <head>     <script src="https://unpkg.com/react@18/umd/react.development.js" crossori...