Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CommonModule vs BrowserModule in angular

I am pretty new to the world of Angular. What is the difference between CommonModule vs BrowserModule and why one should be preferred over the other?

like image 509
Pritam Bohra Avatar asked Apr 05 '18 01:04

Pritam Bohra


People also ask

What is CommonModule in Angular?

CommonModule is used to export all the basic Angular directives and pipes. It is re-exported when we import BrowserModule into our angular application, BrowserModule is automatically imported into our application when we create our Angular application using 'ng new' command.

What is the use of BrowserModule?

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.

Which Angular module is needed for Ng if Ng?

BrowserModule and CommonModule link BrowserModule imports CommonModule , which contributes many common directives such as ngIf and ngFor .

What is BrowserModule withServerTransition?

withServerTransition()linkConfigures a browser-based app to transition from a server-rendered app, if one is present on the page. static withServerTransition(params: { appId: string; }): ModuleWithProviders<BrowserModule>


2 Answers

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 and BrowserModule in your root module.
like image 101
ANewGuyInTown Avatar answered Sep 20 '22 12:09

ANewGuyInTown


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.

like image 37
Sajeetharan Avatar answered Sep 17 '22 12:09

Sajeetharan