Angular2組件開發—爲模板應用樣式(一)

styles - 設置模板樣式

組件既然處於UI層,就應當好看些,好看是構造良好用戶體驗的一部分。Angular2的 組件模板基於HTML,那麼顯然,咱們須要經過樣式表/CSS來調整組件的外觀。javascript

和模板相似,咱們有兩種方法爲組件設置CSS樣式:css

1. 內聯樣式html

能夠使用組件View註解的styles屬性來設置內聯樣式:java

1 @View({
2  styles:[` 3         h1{background:#4dba6c;color:#fff}     
4  `] 5 })

2. 外部樣式bootstrap

也能夠把樣式定義在單獨的文件中:angular2

1 /*ez-greeting.css*/
2 h1{background:#4dba6c;color:#fff}   

而後使用View註解styleUrls屬性引入外部樣式:app

1 @View({
2    styleUrls:["ez-greeting.css"] 3 })

例如:spa

 1 <!doctype html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>template- styles</title>
 6     <script type="text/javascript" src="lib/system@0.16.11.js"></script>
 7     <script type="text/javascript" src="lib/angular2.dev.js"></script>
 8     <script type="text/javascript" src="lib/system.config.js"></script>
 9 </head>
10 <body>
11     <ez-app></ez-app>
12     <script type="module">
13         import {Component,View,bootstrap} from "angular2/angular2";
14         
15         @Component({selector : "ez-app"})
16         @View({
17  styles:[` 18                 div.ez-greeting{font-family:Courier;background:#ede7f6;box-shadow:0 2px 5px 0; }
19                 h1{background:#4dba6c;color:#fff;text-align: center}     
20                 div.content{padding:10px;}
21  `], 22             template : `
23                 <div class="ez-greeting">
24                     <h1>Hello,Angular2</h1>
25                     <div class="content">
26                         <p>
27                             使用ES6開發Angular2應用的一個好處就是,能夠不用拼接樣式字符串了。
28                         </p>
29                         <ul>
30                             <li>在樣式中能夠使用任何標準的CSS語法</li>
31                             <li>若是樣式定義在單獨的文件裏,能夠使用styleUrls引入</li>
32                         </ul>
33                     </div>
34                 </div>
35             `
36         })
37         class EzApp{}
38         
39         bootstrap(EzApp);
40     </script>
41 </body>
42 </html>

結果以下:code

相關文章
相關標籤/搜索