CommonModule vs BrowserModule in angular
The root application module, AppModule, imports BrowserModule so that it can have all the services that are essential to launch and run a browser app.
Components in the AppModule also need to have access to the Angular directive(Arrtibute Directive, Structural Directive) such as *ngIf, *ngFor and *ngSwitch etc. and these directive are available in CommonModule which is automatically exported by the BrowserModule. This is why we have access to the directives in the components defined in AppModule.
And according to the docs
Only root application module, AppModule , should import BrowserModule and all other feature module should import CommonModule because we only need the Angular directives in feature module and not the services that are required to launch the app(Which are already available in RootModule).
According to this:
When it comes to components, pipes and directives, every feature module should import its own dependencies disregarding if the same dependencies were imported in the root module or in any other feature module.
What you have to understand is, with Angular, you create modular application and there are two types of modules. One is root module and another is feature module.
- Root module imports the BrowserModule (if you are rendering in browser). This has the same stuffs as
CommonModule
but also stuffs that are used for rendering. - Now if you are creating a feature module, since you already have BrowserModule imported in your root module, it does not make sense and it's an overhead to import the Browser module in your feature module. Also, importing CommonModule frees feature modules for use on any target platform (e.g. native mobile platform), not just browsers.
That's why you import
CommonModule
in your feature modules andBrowserModule
in your root module.
From the docs
BrowserModule provides services that are essential to launch and run a browser app.
BrowserModule also re-exports CommonModule from @angular/common, which means that components in the AppModule module also have access to the Angular directives every app needs, such as NgIf and NgFor.
whereas
CommonModule (all the basics of Angular templating: bindings, *ngIf, *ngFor…), except in the first app module, because it’s already part of the BrowserModule
Also read this.