根模块 (root module)
每个应用都至少有一个根模块用来引导并运行应用。根模块通常命名为 AppModule。
示例 src/app/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 { }
imports 数组
注意:不要在 imports 数组中加入 NgModule 类型之外的类。
如果有两个同名指令都叫做 HighlightDirective,我们只要在 import 时使用 as 关键字来为第二个指令创建个别名就可以了。
import { HighlightDirective as ContactHighlightDirective} from './contact/highlight.directive';
关于 BrowserModule
每个浏览器中运行的应用都需要 @angular/platform-browser 里的 BrowserModule。 所以每个这样的应用都在其根 AppModule 的 imports 数组中包含 BrowserModule。
NgIf 是在来自 @angular/common 的 CommonModule 中声明的。
CommonModule 提供了很多应用程序中常用的指令,包括 NgIf 和 NgFor 等。
BrowserModule 导入了 CommonModule 并且重新导出了它。 最终的效果是:只要导入 BrowserModule 就自动获得了 CommonModule 中的指令。
declarations 数组
你必须在一个 NgModule 类声明每一个组件,否则浏览器控制台会报错。
不要在 declarations 添加组件、指令和管道以外的其他类型。
不要把 NgModel(或 FORMS_DIRECTIVES)加到 AppModule 元数据的 declarations 数据中!这些指令属于 FormsModule。
组件、指令和管道只能属于一个模块。
永远不要再次声明属于其它模块的类。
bootstrap 数组
通过引导根 AppModule 来启动应用。 在启动过程中,其中一步是创建列在 bootstrap 数组的组件, 并将它们每一个都插入到浏览器的DOM中。
You launch the application by bootstrapping the root AppModule. Among other things, the bootstrapping process creates the component(s) listed in the bootstrap array and inserts each one into the browser DOM.
每个被引导的组件都是它自己的组件树的根。 插入一个被引导的组件通常触发一系列组件的创建并形成组件树。
Each bootstrapped component is the base of its own tree of components. Inserting a bootstrapped component usually triggers a cascade of component creations that fill out that tree.
虽然你可以将多个组件树插入到宿主页面,但并不普遍。 大多数应用只有一个组件树,它们引导单一根组件。
While you can put more than one component tree on a host web page, that's not typical. Most applications have only one component tree and they bootstrap a single root component.
根组件通常命名为 AppComponent。
新闻热点
疑难解答
图片精选