angular tutorials

Difference between declarations, providers, bootstrap and imports in @NgModule ?

This tutorial explains the difference between declarations, providers, bootstrap and imports in @NgModule and Angular Bootstrapping.

Angular Bootstrapping

Bootstrapping or booting is nothing but self-starting process that is supposed to proceed without external input. 

Do you know what exactly happens after you run “ng serve” from the command line ?

Running Angular CLI command “ng serve” will look at file called .angularcli.json’ or ‘angular.json’ to find the entry point to our app. 

How “ng” finds the components that you will create or build ? 

  • “ng serve” will look at file called .angularcli.json’ or ‘angular.json’ to find the entry point to our app. The main.ts is the entry point of our app and it bootstraps our application. The bootstrap process boots an Angular module (app.module.ts)
platformBrowserDynamic().bootstrapModule(AppModule)
  • Therefore, we use AppModule to bootstrap the app. 
  • AppModule specifies which component to use as top-level component.  AppComponent is our top-level component. 

Angular module system – NgModule 

Note, Angular has powerful concept of modules. When you boot an angular app, you are not booting a component directly, instead you create an NgModule which points to the component you want to load. 

Like all decorators, this @NgModule( … ) code adds metadata to the class immediately following (in this case, AppModule). 

Our @NgModule decorator has four keys: declarations, imports, providers, and bootstrap. Think of “NgModule” like a package .

Difference between declarations, providers, bootstrap and imports in @NgModule

declarations – It specifies the components that are defined in this module. You have to declare components in a NgModule before you can use them in your templates. 

providers – providers are used for dependency injection. Therefore, to make a service available to be injected throughout our application.

bootstrap – Basically, it tells Angular that when this module is used to bootstrap an app, we need to load the AppComponent component as the top-level component. 

imports – Put something in your NgModule’s imports if you are going to be using it in your templates or with dependency injection. Note, this imports is different from import statements.

That’s it. Basically, you had learnt what is Angular Bootstrapping, about NgModule and the difference between declarations, providers, bootstrap and imports in @NgModule.

Hope it helped 🙂

Also See:

References:

Leave a Reply

avatar
  Subscribe  
Notify of