Week 04 · Day 01 — 模組系統:認識 NgModule

學習目標

  • 理解 NgModule 的角色
  • 看懂 declarations / imports / providers / bootstrap
  • 讀懂根模組 app.module.ts

重點

NgModule 是什麼 - Angular 用「模組」把相關的元件、服務、功能組織在一起 - 所有元件都必須被宣告在某個模組 - 「宣告了才能用」

根模組 app.module.ts

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

@NgModule({
  declarations: [           // 這個模組擁有哪些元件/指令/管道
    AppComponent,
    HelloComponent
  ],
  imports: [                // 依賴的其他模組
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],            // 這個模組要提供的服務
  bootstrap: [AppComponent] // 啟動時掛載的根元件
})
export class AppModule { }

欄位意義 | 欄位 | 用途 | |------|------| | declarations | 本模組的元件 / 指令 / 管道 | | imports | 引進其他模組的功能 | | providers | 註冊服務(依賴注入) | | bootstrap | 應用程式的根元件 |

實作

  1. 開啟 app.module.ts,找出四個陣列
  2. 檢查你前天建立的 hello 元件是否已加入 declarations
  3. 手動把新元件加入 declarations(沒加入就無法在模板使用)

作業

  • 說出 declarationsimports 的差別
  • 確認所有已建元件都宣告在模組中
  • 解釋 bootstrap 的作用