Component是Directive的子類,它是一個(gè)裝飾器,用于把某個(gè)類標(biāo)記為Angular組件。下面本篇文章就來(lái)帶大家深入了解angular中的@Component裝飾器,希望對(duì)大家有所幫助。
一、 @Component
裝飾器
1.1 @Component
裝飾器的用途
聲明一個(gè)組件時(shí),在組件類的之上要用@Component裝飾器來(lái)告知Angular這是一個(gè)組件?!鞠嚓P(guān)教程推薦:《angular教程》】
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-product-alerts', templateUrl: './product-alerts.component.html', styleUrls: ['./product-alerts.component.css'] }) export class ProductAlertsComponent implements OnInit { constructor() { } ngOnInit() { } }
1.2 @Component
裝飾器的常用選項(xiàng)
@Component
裝飾器繼承于 Directive
,這個(gè)css選擇器用于在模板中標(biāo)記出該指令,并觸發(fā)該指令的實(shí)例化。
1.2.1 繼承自@Directive裝飾器的選項(xiàng)
選項(xiàng) | 類型 | 說(shuō)明 |
---|---|---|
selector | string | css選擇器名,用于在模板中標(biāo)記出該指令(組件),并觸發(fā)其實(shí)例化 |
inputs | string[] | Angular 會(huì)在變更檢測(cè)期間自動(dòng)更新輸入屬性。inputs 屬性定義了一組從 directiveProperty 指向 bindingProperty 的配置項(xiàng): · directiveProperty 用于指定要寫入值的指令內(nèi)屬性。 · bindingProperty 用于指定要從中讀取值的 DOM 屬性。當(dāng)沒(méi)有提供 bindingProperty 時(shí),就假設(shè)它和 directiveProperty 一樣。 |
outputs | string[] | 一組可供事件綁定的輸出屬性。當(dāng)輸出屬性發(fā)出事件時(shí),就會(huì)調(diào)用模板中一個(gè)附加到該事件的處理器。每個(gè)輸出屬性都會(huì)把 directiveProperty 映射到 bindingProperty: · directiveProperty 指定要發(fā)出事件的組件屬性。 · bindingProperty 指定要附加事件處理器的 HTML 屬性。 |
provides | Provider[] | 服務(wù)提供商的集合 |
exportAs | string | 一個(gè)或多個(gè)名字,可以用來(lái)在模板中把該指令賦值給一個(gè)變量。當(dāng)有多個(gè)名字時(shí),請(qǐng)使用逗號(hào)分隔它們。 |
queries | {[key:string]:any} | 配置將要注入到該指令中的一些查詢。內(nèi)容查詢會(huì)在調(diào)用 ngAfterContentInit 回調(diào)之前設(shè)置好。 試圖查詢會(huì)在調(diào)用 ngAfterViewInit 回調(diào)之前設(shè)置好。 |
jit | true | 如果為 true,則該指令/組件將會(huì)被 AOT 編譯器忽略,因此永遠(yuǎn)只會(huì)被 JIT 編譯。這個(gè)選項(xiàng)是為了支持未來(lái)的 Ivy 編譯器,目前還沒(méi)有效果。 |
host | {[key:string]:string} | 使用一組鍵-值對(duì),把類的屬性映射到宿主元素的綁定(Property、Attribute 和事件)。Angular 在變更檢測(cè)期間會(huì)自動(dòng)檢查宿主 Property 綁定。 如果綁定的值發(fā)生了變化,Angular 就會(huì)更新該指令的宿主元素。當(dāng) key 是宿主元素的 Property 時(shí),這個(gè) Property 值就會(huì)傳播到指定的 DOM 屬性。當(dāng) key 是 DOM 中的靜態(tài) Attribute 時(shí),這個(gè) Attribute 值就會(huì)傳播到宿主元素上指定的 Property 去。對(duì)于事件處理: · 它的 key 就是該指令想要監(jiān)聽(tīng)的 DOM 事件。 要想監(jiān)聽(tīng)全局事件,請(qǐng)把要監(jiān)聽(tīng)的目標(biāo)添加到事件名的前面。 這個(gè)目標(biāo)可以是 window、document 或 body。 · 它的 value 就是當(dāng)該事件發(fā)生時(shí)要執(zhí)行的語(yǔ)句。如果該語(yǔ)句返回 false,那么就會(huì)調(diào)用這個(gè) DOM 事件的 preventDefault 函數(shù)。 這個(gè)語(yǔ)句中可以引用局部變量 $event 來(lái)獲取事件數(shù)據(jù)。 |
1.2.2 @Component自己特有的選項(xiàng)
選項(xiàng) | 類型 | 說(shuō)明 |
---|---|---|
changeDetection | ChangeDetectionStrategy | 當(dāng)組件實(shí)例化之后,Angular 就會(huì)創(chuàng)建一個(gè)變更檢測(cè)器,它負(fù)責(zé)傳播組件各個(gè)綁定值的變化。 該策略是下列值之一: · ChangeDetectionStrategy#OnPush(0) 把策略設(shè)置為 CheckOnce(按需)。 · ChangeDetectionStrategy#Default(1) 把策略設(shè)置為 CheckAlways。 |
viewProviders | Provider[] | 定義一組可注入對(duì)象,它們?cè)谝晥D的各個(gè)子節(jié)點(diǎn)中可用 |
moduleId | string | 包含該組件的那個(gè)模塊的 ID。該組件必須能解析模板和樣式表中使用的相對(duì) URL。 SystemJS 在每個(gè)模塊中都導(dǎo)出了 __moduleName 變量。在 CommonJS 中,它可以設(shè)置為module.id。 |
templateUrl | string | 組件模板文件的 URL。如果提供了它,就不要再用 template 來(lái)提供內(nèi)聯(lián)模板了。 |
template | string | 組件的內(nèi)聯(lián)模板。如果提供了它,就不要再用 templateUrl 提供模板了。 |
styleUrls | string[] | 一個(gè)或多個(gè) URL,指向包含本組件 CSS 樣式表的文件。 |
styles | string[] | 本組件用到的一個(gè)或多個(gè)內(nèi)聯(lián) CSS 樣式。 |
animations | any[] | 一個(gè)或多個(gè)動(dòng)畫 trigger() 調(diào)用,包含一些 state() 和 transition() 定義。 |
encapsulation | ViewEncapsulation | 供模板和 CSS 樣式使用的樣式封裝策略。取值為: · ViewEncapsulation.ShadowDom:使用 Shadow DOM。它只在原生支持 Shadow DOM 的平臺(tái)上才能工作。 · ViewEncapsulation.Emulated:使用墊片(shimmed) CSS 來(lái)模擬原生行為。 · ViewEncapsulation.None:使用全局 CSS,不做任何封裝。 如果沒(méi)有提供,該值就會(huì)從 CompilerOptions 中獲取它。默認(rèn)的編譯器選項(xiàng)是 ViewEncapsulation.Emulated。如果該策略設(shè)置為 ViewEncapsulation.Emulated,并且該組件沒(méi)有指定 styles 或 styleUrls,就會(huì)自動(dòng)切換到 ViewEncapsulation.None。 |
interpolation | [string, string] | 改寫默認(rèn)的插值表達(dá)式起止分界符({{ 和 }}) |
entryComponents | Array<Type | any[]> |
preserveWhitespaces | boolean | 為 true 則保留,為 false 則從編譯后的模板中移除可能多余的空白字符。 空白字符就是指那些能在 JavaScript 正則表達(dá)式中匹配 s 的字符。默認(rèn)為 false,除非通過(guò)編譯器選項(xiàng)改寫了它。 |
二、 selector
選擇器
可使用下列形式之一:
element-name
: 根據(jù)元素名選取[attribute]
: 根據(jù)屬性名選取.class
: 根據(jù)類名選取[attribute=value]
: 根據(jù)屬性名和屬性值選取not(sub_selector)
: 只有當(dāng)元素不匹配子選擇器 sub_selector 的時(shí)候才選取selector1, selector2
: 無(wú)論 selector1 還是 selector2 匹配時(shí)都選取
2.1 element-name
: 根據(jù)元素名選取
@Component({ selector: 'app-element', template: './element.component.html', styleUrls: ['./element.component.css'] })
<app-element></app-element>
2.2 [attribute]
: 根據(jù)屬性名選取
@Component({ selector: '[app-element]', template: './element.component.html', styleUrls: ['./element.component.css'] })
<div app-element></div>
2.3 .class
: 根據(jù)類名選取
@Component({ selector: '.app-element', template: './element.component.html', styleUrls: ['./element.component.css'] })
<div class="app-element"></div>
三、 host
: {[key:string]:string}
使用一組鍵-值對(duì),把類的屬性映射到宿主元素的綁定(Property、Attribute 和事件)。
Angular 在變更檢測(cè)期間會(huì)自動(dòng)檢查宿主 Property 綁定。 如果綁定的值發(fā)生了變化,Angular 就會(huì)更新該指令的宿主元素。
- 當(dāng) key 是宿主元素的 Property 時(shí),這個(gè) Property 值就會(huì)傳播到指定的 DOM 屬性。
- 當(dāng) key 是 DOM 中的靜態(tài) Attribute 時(shí),這個(gè) Attribute 值就會(huì)傳播到宿主元素上指定的 Property 去。
- 注意屬性的值默認(rèn)為變量,如果直接使用屬性值,需要加字符串單引號(hào)或者雙引號(hào),變量直接在組件里定義即可
對(duì)于事件處理:
- 它的 key 就是該指令想要監(jiān)聽(tīng)的 DOM 事件。 要想監(jiān)聽(tīng)全局事件,請(qǐng)把要監(jiān)聽(tīng)的目標(biāo)添加到事件名的前面。 這個(gè)目標(biāo)可以是 window、document 或 body。
- 它的 value 就是當(dāng)該事件發(fā)生時(shí)要執(zhí)行的語(yǔ)句。如果該語(yǔ)句返回 false,那么就會(huì)調(diào)用這個(gè) DOM 事件的 preventDefault 函數(shù)。 這個(gè)語(yǔ)句中可以引用局部變量 $event 來(lái)獲取事件數(shù)據(jù)。
3.1 attribute
和 property
- property:dom元素作為對(duì)象附加的內(nèi)容,例如childNodes、firstChild等
- attribute:HTML標(biāo)簽特性是dom節(jié)點(diǎn)自帶的屬性
異同:
- 部分屬性既屬于 property ,又屬于 attribute ,比如 id
- attribute 初始化后不會(huì)再改變; property 默認(rèn)值為初始值,會(huì)隨著 dom 更新
所以在 angular2 中雙向
綁定實(shí)現(xiàn)是由 dom 的 property
實(shí)現(xiàn)的,所以指令綁定的是 property ,但是在某些情況下 dom 不存在某個(gè) property 比如 colspan,rowspan 等,這時(shí)想要綁定 html 標(biāo)簽特性需要用到 attr
:
<table width="100%" border="10px solid"> <tr> <th>Month</th> <th>Savings</th> </tr> <tr> <td [attr.colspan]=colnum>January</td> </tr> <tr> <td [attr.colspan]=colnum>February</td> </tr> </table> let colnum:number = 2;
3.2 使用 host
綁定 class
@Component({ selector: '.app-element', template: './element.component.html', styleUrls: ['./element.component.css'], host: { '[class.default-class]': 'useDefault' }, encapsulation: ViewEncapsulation.None // 讓宿主元素也用上 element.component.css 樣式。否則,默認(rèn)膠囊封裝避免CSS污染。 }) export class AppElementComponent { @Input() useDefault = true; }
<div class="app-element"></div>
3.3 使用 host
綁定 style
@Component({ selector: '.app-element', template: './element.component.html', styleUrls: ['./element.component.css'], host: { '[style.background]': 'inputBackground' } }) export class AppElementComponent { @Input() inputBackground = 'red'; }
<div class="app-element"></div>
3.4 使用 host
綁定事件
@Component({ selector: '.app-element', template: './element.component.html', styleUrls: ['./element.component.css'], host: { '(click)': 'onClick($event)' } }) export class AppElementComponent { public onClick($event) { console.log($event); } }
<div class="app-element"></div>
四、 encapsulation
(封裝)
供模板和 CSS 樣式使用的樣式封裝策略。
4.1 Web Components
通過(guò)一種標(biāo)準(zhǔn)化的非侵入的方式封裝一個(gè)組件,每個(gè)組件能組織好它自身的 HTML 結(jié)構(gòu)、CSS 樣式、JavaScript 代碼,并且不會(huì)干擾
頁(yè)面上的其他元素。
Web Components 由以下四種技術(shù)組成:
- Custom Elements: 自定義元素HTML
- Templates: HTML模板
- Shadow DOM: 影子DOMHTML
- Imports: HTML導(dǎo)入
4.2 Shadow DOM
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Shadow DOM</title> <style type="text/css"> .shadowroot_son { color: #f00; } </style> </head> <body> <p>我不在 Shadow Host內(nèi)</p> <div>Hello, world!</div> <script> // 影子宿主(shadow host) var shadowHost = document.querySelector('.shadowhost'); // 創(chuàng)建影子根(shadow root) var shadowRoot = shadowHost.createShadowRoot(); // 影子根作為影子樹(shù)的第一個(gè)節(jié)點(diǎn),其他的節(jié)點(diǎn)比如p節(jié)點(diǎn)都是它的子節(jié)點(diǎn)。 shadowRoot.innerHTML = '<p>我在 Shadow Host內(nèi)</p>'; </script> </body> <html>
4.3 ViewEncapsulation
ViewEncapsulation 允許設(shè)置三個(gè)可選的值:
- ViewEncapsulation.Emulated: 無(wú) Shadow DOM,但是通過(guò) Angular 提供的樣式包裝機(jī)制來(lái)封裝組件,使得組件的樣式不受外部影響。這是 Angular 的默認(rèn)設(shè)置。
- ViewEncapsulation.ShadowDom: 使用原生的 Shadow DOM 特性
- ViewEncapsulation.None: 無(wú) Shadow DOM,并且也無(wú)樣式包裝
4.3.1 ViewEncapsulation.None
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h4>Welcome to Angular World</h4> <p class="greet">Hello {{name}}</p> `, styles: [` .greet { background: #369; color: white; } `], encapsulation: ViewEncapsulation.None // None | Emulated | ShadowDom }) export class AppComponent { name: string = 'Semlinker'; }
ViewEncapsulation.None
設(shè)置的結(jié)果是沒(méi)有 Shadow DOM
,并且所有的樣式都應(yīng)用到整個(gè)
document
,換句話說(shuō),組件的樣式會(huì)受外界影響
,可能被覆蓋
掉。
4.3.2 ViewEncapsulation.Emulated
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'my-app', ..., encapsulation: ViewEncapsulation.Emulated // None | Emulated | ShadowDom }) export class AppComponent { name: string = 'Semlinker'; }
ViewEncapsulation.Emulated
設(shè)置的結(jié)果是沒(méi)有 Shadow DOM
,但是通過(guò) Angular
提供的樣式包裝機(jī)制
來(lái)封裝組件,使得組件的樣式不受外部影響
。雖然樣式仍然是應(yīng)用到整個(gè) document
,但 Angular 為 .greet
類創(chuàng)建了一個(gè) [_ngcontent-cmy-0]
選擇器??梢钥闯?,我們為組件定義的樣式,被 Angular 修改了
。其中的 _nghost-cmy- 和 _ngcontent-cmy-
用來(lái)實(shí)現(xiàn)局部的樣式
。
4.3.3 ViewEncapsulation.ShadowDom
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'my-app', ..., encapsulation: ViewEncapsulation.ShadowDom // None | Emulated | ShadowDom }) export class AppComponent { name: string = 'Semlinker'; }
ViewEncapsulation.ShadowDom
設(shè)置的結(jié)果是使用原生的 Shadow DOM
特性。Angular 會(huì)把組件按照瀏覽器支持的 Shadow DOM 形式渲染
。