简体   繁体   中英

NgModule and FormModule importing on every module?

So I'm using RC5, and when embracing things seems to go pretty decently for now I ran into an issue which I'm not sure if I'm doing something wrong or is working as intended;

Before it was possible to make form directives etc. globally available. Nowadays we started using NgModule. It seems though that I can't use FormsModule and ReactiveFormsModule globally, either in AppModule nor in a SharedModule. I need to import it in every single module I create.

Is this as intended?

According to this NgModule doc it is as intended,

  • so if you are using multiple NgModule heirarchy in your app, you will need to create a SharedModule and import/export all the global Modules/Components/Directives/Pipes in it.

  • then import this module in every Module that you want to share it with.


You can read the docs for more clarification.

You should add FormsModule and ReactiveFormsModule to your SharedModule exports, then you need to import your SharedModule into your other modules. That way, you will be able to use desired directives globally.

I'm using FormsModule and ReactiveFormsModule globally, in my app.module.ts like this:

 imports: [ // module dependencies
         BrowserModule, routing,
         FormsModule, ReactiveFormsModule, HttpModule,...
     ]

You can export the class with the directives which you need, an example of this is:

  1. Create a file ngforms.module.ts (can be on the root app)
  2. Write this:
 import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports:[ FormsModule, ReactiveFormsModule, ], exports:[ FormsModule, ReactiveFormsModule, ] }) export class NgFormModule {}
  1. In every module or submodule for your app you have to import and call it
import { NgFormModule } from './ngform.module'; imports: [ //Angular material BrowserAnimationsModule, //Angular (forms) NgFormModule ],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM