NgModule 用于描述应用的各个部分如何组织在一起。 每个应用又至少一个 Angular 模块,根模块就是你用来启动此应用的模块。 按照惯例,它通常命名为 AppModule
。
如果你使用 CLI 来生成一个应用,其默认的 AppModule
是这样的:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
declarations:
该模块的 declarations
数组告诉 Angular 哪些组件属于该模块。 当你创建更多组件时,也要把它们添加到 declarations
中。
每个组件都应该(且只能)声明(declare)在一个 NgModule
类中。 如果你使用了未声明过的组件,Angular 就会报错。
declarations
数组只能接受可声明对象。可声明对象包括组件、指令和管道。 一个模块的所有可声明对象都必须放在 declarations
数组中。 可声明对象必须只能属于一个模块,如果同一个类被声明在了多个模块中,编译器就会报错。
import:
模块的 imports
数组只会出现在 @NgModule
元数据对象中。 它告诉 Angular 该模块想要正常工作,还需要哪些模块。
exports:
可供导入了自己的模块使用的可声明对象(组件、指令、管道类)的列表。
providers:
providers
数组中列出了该应用所需的服务。
bootstrap:
通常,在这个列表中只有一个组件,也就是应用的根组件。Angular也可以引导多个引导组件,它们每一个都在宿主页面中有自己的位置。
entryComponent:
动态加载组件的时候,将组件加入到declarations中后,还需要在此再加入一遍。