VOOZH about

URL: https://www.geeksforgeeks.org/angular-js/what-is-the-difference-between-declarations-providers-and-import-in-ngmodule/

⇱ What is the difference between declarations, providers, and import in NgModule? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

What is the difference between declarations, providers, and import in NgModule?

Last Updated : 24 Sep, 2020

Let us first discuss about these terms:

  • Declarations: 
    • Declarations are used to declare components, directives, pipes that belongs to the current module. 
    • Everything inside declarations knows each other.
    • Declarations are used to make directives (including components and pipes) from the current module available to other directives in the current module.
    • Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.
  • Providers: 
    • Providers are used to make services and values known to dependency injection.
    • They are added to the root scope and they are injected to other services or directives that have them as dependency.
  • Imports:
    • Imports makes the exported declarations of other modules available in the current module.
    • It is used to import supporting modules likes FormsModule, RouterModule, CommonModule etc.

Differences:

Declarations

Providers

Imports

Declarations are used to make directives.Providers are used to make services.Imports makes the exported declarations of other modules available in the current module.
Used to declare components, directives, pipes that belongs to the current module.Used to inject the services required by components, directives, pipes in our module.Used to import supporting modules likes FormsModule, RouterModule, etc.
Ex. AppComponent.Ex. StateService.Ex. BrowserModule.

Defined in Declarations array in @NgModule

@NgModule({

 declarations: [  ],

 )}

Defined in Providers array in @NgModule.

@NgModule({

providers: [ ],

)}

Defined in imports array in @NgModule.

@NgModule({

imports: [],

)}

An example in which all three declarations, imports and providers are used:

The providers used in this project is custom service named UserService.

ng g s User

user.service.ts

This UserService is used as provider in app.module.ts.

app.module.ts

app.component.html

Output:

👁 Image
Comment
Article Tags:

Explore