Angular模块化
模块是组织应用和使用外部库扩展应用的最佳途径
NgModule
把组件、指令和管道打包成内聚的功能块,每个模块聚焦于一个特性区域、业务领域、工作流或通用工具。
模块还可以把服务加到应用中。 这些服务可能是内部开发的(比如你自己写的),或者来自外部的(比如 Angular 的路由和 HTTP 客户端)。
基本模块剖析
当你使用 Angular CLI 命令 ng new
生成一个应用时,其默认的 AppModule
是这样的:
// imports
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
// @NgModule decorator with its metadata
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent],
entryComponents: []
})
export class AppModule {}
@NgModule
装饰器表明 AppModule
是一个 NgModule
类。 @NgModule
获取一个元数据对象,它会告诉 Angular 如何编译和启动本应用。
- declarations(可声明对象表) —— 那些属于本
NgModule
的组件、指令、管道。用于指示该模块的内部编译 - imports(导入表) —— 导入的其他/第三方模块,之后才能在本模块中使用。
- exports(导出表) —— 那些能在其它模块的组件模板中使用的可声明对象的子集。
- providers —— 可在本模块中使用的可注入对象。
- bootstrap(应用的主视图) —— 根组件,又是程序的入口组件,Angular创建并插入
index.html
宿主页面。它是应用中所有其它视图的宿主。只有根模块才应该设置这个bootstrap
属性。 - entryComponents —— The set of components to compile when this NgModule is defined, so that they can be dynamically loaded into the view. For each component listed here, Angular creates a
ComponentFactory
and stores it in theComponentFactoryResolver
.
常用模块
NgModule | 导入自 | 为何使用 |
---|---|---|
BrowserModule | @angular/platform-browser | 当你想要在浏览器中运行应用时 |
CommonModule | @angular/common | 当你想要使用 NgIf 和 NgFor 时 |
FormsModule | @angular/forms | 当要构建模板驱动表单时(它包含 NgModel ) |
ReactiveFormsModule | @angular/forms | 当要构建响应式表单时 |
RouterModule | @angular/router | 要使用路由功能,并且你要用到 RouterLink ,.forRoot() 和 .forChild() 时 |
HttpClientModule | @angular/common/http | 当你要和服务器对话时 |