模块
Angular很重要的概念之一仍然是模块。Angular整个框架就是由很多个模块组成的,而不同的模块需要从不同的地方导入。打开package.json
文件,可以看到依赖的angular包可能是这样的:
"@angular/common": "^2.3.1",
"@angular/compiler": "^2.3.1",
"@angular/core": "^2.3.1",
"@angular/forms": "^2.3.1",
"@angular/http": "^2.3.1",
"@angular/platform-browser": "^2.3.1",
"@angular/platform-browser-dynamic": "^2.3.1",
"@angular/router": "^3.3.1",
来简单看下这些angular包中包含了哪些常用的模块(至少目前为止,我觉得常用的)。
- @angular/core:这里包含了很多常用的模块
- NgModule:模块定义装饰器
- Component:组件定义装饰器
- Directive:指令定义装饰器
- Pipe :管道定义装饰器
- PipeTransform:管道接口
- Injectable:服务定义装饰器
- ElmentRef:元素引用
- ViewChild:获取子元素
- Render:渲染
- Input:接受参数输入
- Output:事件输出
- EventEmitter:触发自定义事件
- @angular/common
- CommonModule:通用模块,包含内置指令ngIf,ngFor
- @angular/forms
- FormsModule:定义模版驱动表单
- ReactiveFormsModule:定义响应式表单
- FormGroup, FormArray, FormControl, FormBuilder:响应式表单元素
- Validators:表单校验
- @angular/http
- HttpModule:http请求模块
- @angular/router
- RouterModule 路由模块
- Routes 路由数据结构
- @angular/platform-browser
- platformBrowser:AoT编译
- BrowserModule:浏览器支持,注意该模块导入了CommonModule,然后导出去,所以引用了这个模块也就引用了CommonModule
- @angular/platform-browser-dynamic
- platformBrowserDynamic:JIT编译
以上模块都是Angular框架中的自带模块,而我们开发的完整单元也是模块。一个应用中至少要有一个模块,也就是根模块。 一些共享的功能属性我们可以抽象出来,成为共享模块。然后就是一些特性模块了。
模块的组成由组件,服务,指令,管道等等组成,这些概念会在下面讲到。定义模块的语法如下:
@NgModuel({
declarations: [], // 用到的组件,指令,管道
providers: [], // 依赖注入服务
imports: [], // 导入需要的模块
exports: [], // 导出的模块,跨模块交流
entryComponents: [] // 需提前编译好的模块
bootstrap: [] // 设置根组件
})
export class AppModule { }
所有用到的组件,指令,管道,模块都需要事先在模块中声明好,才能在具体组件中使用。服务可以在模块,组件,指令中的
providers
声明,也可以直接在运行时提供(参见Trotyl Yu的例子)。
一般情况下,在根模块的bootstrap
中设置启动的根组件即可,但也可以动态处理(参见Trotyl Yu的例子)。
那如何启动根模块呢?
在入口脚本中,也就是Angular Cli项目中的main.ts
中,启动如下:
// 导入需要模块
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
// 根模块
import { AppModule } from './app/app.module';
// 编译启动模块
platformBrowserDynamic().bootstrapModule(AppModule);
至此,我们对模块有所了解,也知道了模块的定义。
想要整理更多的碎片知识,扫码关注下面的公众号,让我们在哪里接着唠!