Angular 2 - 模块



模块用于 Angular JS 中,为应用程序设置逻辑边界。因此,无需将所有代码都编写到一个应用程序中,而是可以将所有内容构建到单独的模块中,以分离应用程序的功能。让我们检查一下添加到演示应用程序中的代码。

在 Visual Studio Code 中,转到应用程序文件夹中的 app.module.ts 文件夹。这被称为根模块类。

Root Module Class

app.module.ts 文件中将存在以下代码。

import { NgModule }      from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser';  
import { AppComponent }  from './app.component';  

@NgModule ({ 
   imports:      [ BrowserModule ], 
   declarations: [ AppComponent ], 
   bootstrap:    [ AppComponent ] 
}) 
export class AppModule { } 

让我们详细了解每一行代码。

  • import 语句用于从现有模块导入功能。因此,前三个语句用于将 NgModule、BrowserModule 和 AppComponent 模块导入此模块。

  • NgModule 装饰器用于稍后定义导入、声明和引导选项。

  • 对于任何基于 Web 的 Angular 应用程序,BrowserModule 默认都是必需的。

  • bootstrap 选项告诉 Angular 要引导哪个组件到应用程序中。

一个模块由以下部分组成:

  • Bootstrap 数组 - 用于告诉 Angular JS 需要加载哪些组件才能在应用程序中访问其功能。将组件包含在 bootstrap 数组中后,需要声明它们,以便可以在 Angular JS 应用程序中的其他组件中使用它们。

  • Export 数组 - 用于导出组件、指令和管道,然后可以在其他模块中使用它们。

  • Import 数组 - 与 export 数组一样,import 数组可用于从其他 Angular JS 模块导入功能。

广告