Angular - 模块



Angular 中的模块是指一个可以将组件、指令、管道和服务等与应用程序相关的部分组合在一起的地方。

如果您正在开发一个网站,则页眉、页脚、左侧、中心和右侧部分将成为模块的一部分。

要定义模块,我们可以使用 NgModule。当您使用 Angular –cli 命令创建一个新项目时,ngmodule 默认会在 **app.module.ts** 文件中创建,其外观如下所示:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';

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

NgModule 需要如下导入:

import { NgModule } from '@angular/core';

ngmodule 的结构如下所示:

@NgModule({ 
   declarations: [
      AppComponent, 
      NewCmpComponent 
   ],
   imports: [ 
      BrowserModule, 
      AppRoutingModule 
   ], 
   providers: [], 
   bootstrap: [AppComponent] 
})

它以 **@NgModule** 开头,包含一个具有 declarations、imports、providers 和 bootstrap 的对象。

声明 (Declaration)

这是一个已创建的组件数组。如果创建了任何新组件,它将首先被导入,并且引用将包含在 declarations 中,如下所示:

declarations: [ 
   AppComponent,  
   NewCmpComponent 
]

导入 (Import)

这是一个应用程序中需要使用的模块数组。它也可以被 Declaration 数组中的组件使用。例如,现在在 @NgModule 中,我们看到导入了 BrowserModule。如果您的应用程序需要表单,您可以使用以下代码包含该模块:

import { FormsModule } from '@angular/forms';

**@NgModule** 中的导入将如下所示:

imports: [ 
   BrowserModule, 
   FormsModule 
]

提供程序 (Providers)

这将包含已创建的服务。

引导 (Bootstrap)

这包括用于启动执行的主应用程序组件。

广告
© . All rights reserved.