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

前端 未结 6 1031
面向向阳花
面向向阳花 2020-12-02 03:39

I am trying to understand Angular (sometimes called Angular2+), then I came across @Module:

  1. Imports

  2. Declarations

  3. <
6条回答
  •  独厮守ぢ
    2020-12-02 04:09

    Angular @NgModule constructs:

    1. import { x } from 'y';: This is standard typescript syntax (ES2015/ES6 module syntax) for importing code from other files. This is not Angular specific. Also this is technically not part of the module, it is just necessary to get the needed code within scope of this file.
    2. imports: [FormsModule]: You import other modules in here. For example we import FormsModule in the example below. Now we can use the functionality which the FormsModule has to offer throughout this module.
    3. declarations: [OnlineHeaderComponent, ReCaptcha2Directive]: You put your components, directives, and pipes here. Once declared here you now can use them throughout the whole module. For example we can now use the OnlineHeaderComponent in the AppComponent view (html file). Angular knows where to find this OnlineHeaderComponent because it is declared in the @NgModule.
    4. providers: [RegisterService]: Here our services of this specific module are defined. You can use the services in your components by injecting with dependency injection.

    Example module:

    // Angular
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    
    // Components
    import { AppComponent } from './app.component';
    import { OfflineHeaderComponent } from './offline/offline-header/offline-header.component';
    import { OnlineHeaderComponent } from './online/online-header/online-header.component';
    
    // Services
    import { RegisterService } from './services/register.service';
    
    // Directives
    import { ReCaptcha2Directive } from './directives/re-captcha2.directive';
    
    @NgModule({
      declarations: [
        OfflineHeaderComponent,,
        OnlineHeaderComponent,
        ReCaptcha2Directive,
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
      ],
      providers: [
        RegisterService,
      ],
      entryComponents: [
        ChangePasswordComponent,
        TestamentComponent,
        FriendsListComponent,
        TravelConfirmComponent
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

提交回复
热议问题