Component 是一個個 UI 元件的小碎塊,而 Module 是集中這些小碎塊的收集者。 在[Angular - 組件與插值與屬性綁定](https://hackmd.io/@un/Hy3-IhsN3)已經有簡單的介紹過組件的組成,在這篇文章會更深入的了解 Component 與 Module。 ## Component Component 是負責定義與控制畫面(View)的重要元件。 白話來說組件是由 html + css + logic 組成的,但更深入一點來說,他是由 **template + metadata + class** 組成的。 那麼 **metadata** 是什麼? 這就需要先介紹什麼是 Decorators 了! ### @Component Decorators 什麼是裝飾器(Decorators)?其實裝飾器一開始是 Typescript 為了 Angular 先行加入的功能,JS 則是直到 ES7 才加入的新功能。 裝飾器讓我們可以在設計時期透過註記的方式修改類別與屬性,傳入 `@Component`或是其他裝飾器中的物件,在 Angular 中,稱為**metadata**(中繼資料),Metadata 要告訴 Angular,怎麼處理接下來的類別。 #### @Component 中有什麼? - selector: 他其實可以解釋為 html 中的自定義標籤,他為了讓 component 可以在 template 找到自己應該要擺放的位置,再創建出 component 的實體後,安插於你定義的 selector 當中。像是下方的程式碼中,component 就會去找位於 template 中 `<app-root></app-root>` 的標籤。 - templateUrl: 顧名思義,就是 template 的檔案位置 - template: 讓你可以直接將 HTML 語法撰寫於此(但是不建議使用) - styleUrls: CSS 的檔案位置,使用陣列的方式接收 - styles :`[`h1{color:red}`]` 讓你可以直接將 CSS 撰寫於此 (不建議使用) ```javascript= @Component({ selector: 'app-root', templateUrl: './app.component.html', // 你也可以直接將 html 寫在這裡 // template:`<h1> This is title </h1>` styleUrls: ['./app.component.css'], // 你也可以直接將 css 寫在這裡 // styles:[`h1{color:red}`] }) ``` ### Component Class 在組件中,我們會需要撰寫邏輯,使 template 可以根據資料和程式邏輯呈現相對應的畫面。 那麼我們這段程式碼要撰寫在哪裡呢?答案就是寫在 component 的 class 中。 ```javascript= export class AppComponent { // 定義組件資料: taskTitle: string = ''; tasks: Array<{ taskTitle: string; isCheck: boolean; }> = []; // 定義組件邏輯: handleChecked(index: any) { this.tasks[index].isCheck = !this.tasks[index].isCheck; } } ``` ## 有了 Component,Module呢? 在我們創建了一個 Anuglar 專案後,會看見檔案中有一個文件名 `app.module.ts` 這就是定義 module 的文件。 其中 BrowserModule 是使你可以在瀏覽器中運行你的專案,並且導入了 CommonModule,它提供了許多常用的 directive 例如 ngIf, ngFor 等等。 想了解更多關於 BrowserModule 可以前往[這篇文章](https://ithelp.ithome.com.tw/articles/10263277)來了解更多詳細資訊 ```javascript = // 導入模組需要使用之套件 import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; // 你定義的路由以及屬於此模組的組件 import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; ``` ### 成為一個 Module 的類 要使這個 Class 成為 Angular 中的 module,首先我們需要從`@angular/core`導入 `NgModule` ,並且使用 `@ngModule` 這個裝飾器,來宣告我目前定義的這個Class 是一個 module(模組)。 ### @ngModule Decorators ```javascript= @NgModule({ declarations: [AppComponent], imports: [BrowserModule, AppRoutingModule], providers: [], bootstrap: [AppComponent], }) ``` - declarations: 在這裡放置屬於這個模組的 Component(組件)、Directors(指令)、Pipes(管道) - imports: 在這裡放置此模組有引入的其他模組 - providers: 引入此模組有使用到的 service - bootstrap: 用來定義最上層的 component 在之後我們可能會常常接觸到路由的模組,也就是 `routing module` 以上關於 component 以及 module 的更多介紹就到這邊。 接下來就會開始進行小小的 coding啦~ ###### tags: `Angular`