根模塊 (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。
新聞熱點
疑難解答
圖片精選