# Day12 【牙起來】 Component、Directive、Service簡介 - Decorator 裝飾器 這篇沒有實作課,只有一些小理論~ 整理各種Angular部件 ## 元件 Component 打造可重複利用的元件 #### 指令 產生一個新的`Component`的指令 > ng g c test (ng generate component test) #### 檔案 一共會產生出四個檔案 * `test.component.css` * `test.component.html` * `test.component.ts` * `test.component.spec.ts`  #### 核心 部件的靈魂在`test.component.ts`中 ```typescript= @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) ``` 一個元件必定需要有 `selector`、`template` 這兩樣東西 元件可以沒有css,但不能沒有HTML,因為一個**元件**需要有畫面View,就要有HTML架構 #### 引用 要引用時,在**主樣板**引用該元件標籤 ```html= <app-test></app-test> ```  --- ## 指示 Directive 可將特定邏輯或檢核寫在指示中,套在要用到的樣板元素上 #### 指令 產生一個新的`Directive`的指令 > ng g d t (ng generate directive test) #### 檔案 會產生出兩個檔案 * `test.directive.ts` * `test.directive.spec.ts`  沒有HTML樣板,因為他不是單一個網頁元件,沒有可呈現畫面的空間 #### 核心 部件的靈魂在`test.directive.ts`中 ```typescript= @Directive({ selector: '[appTest]' }) ``` #### 引用 引用方式,在主樣板引用該指示屬性 就像新增一個自訂屬性 ```html= <h2 appTest>商店區塊</h2> ```  --- ## 服務 Service 可將打API的請求、單一化的實例寫在服務中 #### 指令 產生一個新的`Service`的指令 > ng g d t (ng generate directive test) #### 檔案 會產生出兩個檔案 * `test.service.ts` * `test.service.spec.ts`  #### 核心 部件的靈魂在`test.service.ts`中 ```typescript= @Injectable({ providedIn: 'root' }) ``` `providedIn` 的參數可為: `'root'`、`'platform'`、`'any'`、`null` 也可省略`providedIn`參數,變成只有這樣  #### 引用 引用方式,在要使用到此服務的元件程式的`constructor()`中,注入依賴 ```typescript= ... constructor( public testService: TestService, ) { } ... ```  > 到這邊,Angular已完成88.8%進度
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up