Angular9 常用模块
Angular 应用至少需要一个充当根模块使用的模块。 如果你要把某些特性添加到应用中,可以通过添加模块来实现。 下列是一些常用的 Angular 模块,其中带有一些其内容物的例子:
| 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 | 当你要和服务器对话时 |
导入模块
当你使用这些 Angular 模块时,在 AppModule(或适当的特性模块)中导入它们,并把它们列在当前 @NgModule 的 imports 数组中。比如,在 Angular CLI 生成的基本应用中,BrowserModule 会在 "app.module.ts" 中 AppModule 的顶部最先导入。
/* import modules so that AppModule can access them */
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [ /* add modules here so Angular knows to use them */
BrowserModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
文件顶部的这些导入是 JavaScript 的导入语句,而 @NgModule 中的 imports 数组则是 Angular 特有的。
BrowserModule 和 CommonModule
BrowserModule 导入了 CommonModule,它贡献了很多通用的指令,比如 ngIf 和 ngFor。 另外,BrowserModule 重新导出了 CommonModule,以便它所有的指令在任何导入了 BrowserModule 的模块中都可以使用。
对于运行在浏览器中的应用来说,都必须在根模块中 AppModule 导入 BrowserModule,因为它提供了启动和运行浏览器应用时某些必须的服务。BrowserModule 的提供者是面向整个应用的,所以它只能在根模块中使用,而不是特性模块。 特性模块只需要 CommonModule 中的常用指令,它们不需要重新安装所有全应用级的服务。
如果你把 BrowserModule 导入了惰性加载的特性模块中,Angular 就会返回一个错误,并告诉你要改用 CommonModule。
