Skip to content

模組 | Angular 新手練功日誌

· 6 min

今天要介紹傳統 Angular 建立應用程式的方式 - 模組(Module)。

Angular Module#

Angular 模組是過去 Angular 應用程式的基本組織,用於將相關的組件、指令、管道和服務等功能集合在一起。而基於模組的元件需要在模組中註冊,並且只能在該模組中使用。

目前版本若要建立基於模組的元件,需要在 @Component 裝飾器中將 standalone 屬性設為 false

@Component({
...
  standalone: false, // 設定為基於模組的元件
})

建立方式#

一開始,我們先在 Angular 根元件附近建立一個根模組 Root Module,命名為 app.module.ts

模組需要有兩個關鍵部分:

@NgModule#

@NgModule 是定義了模組的相關設定。

裝飾器中常用的屬性有:

如果沒有正確引入BrowserModule 或 CommonModule  ,Angular 應用會出現錯誤。

  • 在根模組中必須引入 BrowserModule,否則應用無法在瀏覽器中正確啟動
  • 在子模組中必須引入 CommonModule,否則子模組中的元件無法使用 Angular 提供的常用指令和管道。

根模組範例

import { NgModule } from '@angular/core';
import { App } from './app';
import { HeaderComponent } from './header/header.component';
import { RouterOutlet } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
  declarations: [App, HeaderComponent],
  imports: [BrowserModule, RouterOutlet],
  bootstrap: [App],
})
export class AppModule {}

子模組範例

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TaskListComponent } from './task-list/task-list.component';
import { TaskItemComponent } from './task-item/task-item.component';
@NgModule({
declarations: [TaskListComponent, TaskItemComponent],
imports: [CommonModule],
exports: [TaskListComponent, TaskItemComponent] // 導出子元件
})
export class TasksModule {}

建立模組後,需要在 main.ts 中啟動應用程式。

import { platformBrowser } from '@angular/platform-browser';
import { AppModule } from './app/app.module';
platformBrowser().bootstrapModule(AppModule)
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);

快速建立模組#

Terminal window
ng generate module <module-name>
ng g m <module-name> // 簡寫

獨立元件和模組的比較#

獨立元件

模組

由於模組的複雜性且不易排查問題等原因,Angular 官方目前推薦使用獨立元件來建立應用程式,但舊專案仍然會使用模組的方式來組織元件,因此了解模組的使用方式仍然很重要。

專案實作#

今天的目標是將昨日的獨立元件改為基於模組的元件。

day 5 分享

結論#

這篇文章介紹了 Angular 模組的基本概念和使用方式,讓大家了解如何使用模組。下一篇文章會介紹元件內部相關的使用方式