Angular 2 中的元件(一)
簡述
元件是Angular 2 眾多好的理念之一。
在Angular apps中,我們使用HTML的標籤來編寫我們的互動應用。但是瀏覽器只理解一些標籤,像select或者form等一些瀏覽器建立者定義的標籤。
我們如何讓瀏覽器認識新的標籤呢?如果我們想使用標籤來展示天氣怎麼辦?又或者我們想使用標籤來建立一個登入面板?我們可以使用Angular的元件,元件可以讓瀏覽器認識我們定製的標籤。
建立元件的命令
讓我們來建立第一個component,當我們建立好這個component,我們將能夠在HTML文件中使用它,如下所示:
<app-hello-world></app-hello -world>
可以使用angular-cli的generate命令建立component,使用下面的命令我們可以建立一個名為hello-world的component,命令如下:
$ ng generate component hello-world
從輸出結果可以看出建立了哪些檔案,結果如下:
installing component
create src/app/hello-world/hello-world.component.css
create src/app/hello-world/hello-world.component.html
create src/app/hello-world/hello-world.component .spec.ts
create src/app/hello-world/hello-world.component.ts
update src/app/app.module.ts
名為hello-world.component.ts的TypeScript檔案定義了一個元件。用編輯器開啟內容如下:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello-world',
templateUrl: './hello-world.component.html',
styleUrls: ['./hello-world.component.css' ]
})
export class HelloWorldComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
一個基本的元件有兩部分:
1. 一個元件註釋
2. 一個元件定義類
元件TypeScript檔案中的內容
如果之前不瞭解TypeScript語言,則hello-world.component.ts檔案中內容看起來可能頭大,但是不用擔心,下面一步一步的說一下。
匯入依賴
hello-world.component.ts檔案開始的import語句定義了我們寫程式碼時需要用到的模組。檔案中的 import語句從”@anaular/core”模組匯入了:Component和OnInit。import語句的格式如下:
import {匯入的內容} from 模組
在匯入語句中{}的意思是解構,解構是TypeScript和ES6提供的特性,以後的章節會深入的探討。
Component 註釋
匯入過依賴之後,我們需要宣告元件。hello-world.component.ts檔案中下面的程式碼就是Component註釋:
@Component({
selector: 'app-hello-world',
templateUrl: './hello-world.component.html',
styleUrls: ['./hello-world.component.css']
})
當使用@Component註釋在HelloWorldComponent類上時代表宣告HelloWorldComponent是一個元件。
註釋中的selector: ‘app-hello-world’程式碼可以讓我們通過標籤來訪問到元件。
註釋中templateUrl: ‘./hello-world.component.html’程式碼的意思是:標籤解析時會使用’./hello-world.component.html’中的程式碼。可以看一下hello-world.component.html檔案的內容:
<p>
hello-world works!
</p>
宣告註釋時我們有兩種方式定義模板,使用templateUrl或者template。上面註釋的宣告就是使用的templateUrl,使用template的方式如下:
@Component({
selector: 'app-hello-world',
template: `
<p>
hello-world works inline!
</p>`,
styleUrls: ['./hello-world.component.css']
})
注:定義tmplate的值時需要在將內容放入反引號中,反引號的語法是在ES6中引入的用來支援多行字串。
至於是用template還是templateUrl,根據單一職責原則,建議使用templateUrl。
註釋中styleUrls: [‘./hello-world.component.css’]代表元件被渲染時將使用hello-world.component.css檔案中定義的樣式。Angular 2有一個概念叫樣式封裝,意思就是樣式被指定到特定的元件上時它只能僅僅對這一元件起作用。以後會有樣式封裝更深入的討論。styleUrls和template的值有不同,styleUrls的值可以是陣列,這樣我們就可以使用多個樣式來渲染一個元件。
載入元件
建立元件之後,如果我們立即在瀏覽器裡訪問我們的應用,你會發現沒有什麼變化。這是因為你只建立了元件,而沒有使用它。
我們需要將元件標籤增加到已經可以被瀏覽器渲染的模板中。我們可以將標籤放入src/app/app.component.html中,因為app.component.html檔案是index.html中標籤對應的模板檔案。修改後的app.component.html如下:
<h1>
{{title}}
<app-hello-world></app-hello-world>
</h1>
這時使用瀏覽器訪問我們的應用看到的如下:
app works!
hello-world works!
自定義的元件已經很好的在瀏覽器裡工作了,後面元件(二)會新增一些資料在元件裡看看是什麼效果。
歡迎關注,互相交流學習