在介紹Angular Component以前,咱們先簡單瞭解下W3C Web Componentscss
<template>
標籤去預約義一些內容,但並不加載至頁面,而是使用 JS 代碼去初始化它;<link rel="import" href="example.html" />
。歸納來講就是,能夠建立自定義標籤來引入組件是前端組件化的基礎,在頁面引用 HTML 文件和 HTML 模板是用於支撐編寫組件視圖和組件資源管理,而 Shadow DOM 則是隔離組件間代碼的衝突和影響。html
定義hello-component前端
<template id="hello-template"> <style> h1 { color: red; } </style> <h1>Hello Web Component!</h1> </template> <script> // 指向導入文檔,即本例的index.html var indexDoc = document; // 指向被導入文檔,即當前文檔hello.html var helloDoc = (indexDoc._currentScript || indexDoc.currentScript).ownerDocument; // 得到上面的模板 var tmpl = helloDoc.querySelector('#hello-template'); // 建立一個新元素的原型,繼承自HTMLElement var HelloProto = Object.create(HTMLElement.prototype); // 設置 Shadow DOM 並將模板的內容克隆進去 HelloProto.createdCallback = function() { var root = this.createShadowRoot(); root.appendChild(indexDoc.importNode(tmpl.content, true)); }; // 註冊新元素 var hello = indexDoc.registerElement('hello-component', { prototype: HelloProto }); </script>
使用hello-componentgit
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-COMPATIBLE" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="author" content="賴祥燃, laixiangran@163.com, http://www.laixiangran.cn"/> <title>Web Component</title> <!--導入自定義組件--> <link rel="import" href="hello.html"> </head> <body> <!--自定義標籤--> <hello-component></hello-component> </body> </html>
從以上代碼可看到,hello.html 爲按標準定義的組件(名稱爲 hello-component ),在這個組件中有本身的結構、樣式及邏輯,而後在 index.html 中引入該組件文件,便可像普通標籤同樣使用。github
Angular Component屬於指令的一種,能夠理解爲擁有模板的指令。其它兩種是屬性型指令和結構型指令。web
@Component({ selector: 'demo-component', template: 'Demo Component' }) export class DemoComponent {}
@component
進行裝飾才能成爲Angular組件。selector
、template
等,下文將着重講解每一個元數據的含義。DOM
元素就是此組件實例的宿主元素。名稱 | 類型 | 做用 |
---|---|---|
animations | AnimationEntryMetadata[] |
設置組件的動畫 |
changeDetection | ChangeDetectionStrategy |
設置組件的變化監測策略 |
encapsulation | ViewEncapsulation |
設置組件的視圖包裝選項 |
entryComponents | any[] |
設置將被動態插入到該組件視圖中的組件列表 |
interpolation | [string, string] |
自定義組件的插值標記,默認是雙大括號{{}} |
moduleId | string |
設置該組件在 ES/CommonJS 規範下的模塊id,它被用於解析模板樣式的相對路徑 |
styleUrls | string[] |
設置組件引用的外部樣式文件 |
styles | string[] |
設置組件使用的內聯樣式 |
template | string |
設置組件的內聯模板 |
templateUrl | string |
設置組件模板所在路徑 |
viewProviders | Provider[] |
設置組件及其全部子組件(不含ContentChildren)可用的服務 |
名稱 | 類型 | 做用 |
---|---|---|
exportAs | string |
設置組件實例在模板中的別名,使得能夠在模板中調用 |
host | {[key: string]: string} |
設置組件的事件、動做和屬性等 |
inputs | string[] |
設置組件的輸入屬性 |
outputs | string[] |
設置組件的輸出屬性 |
providers | Provider[] |
設置組件及其全部子組件(含ContentChildren)可用的服務(依賴注入) |
queries | {[key: string]: any} |
設置須要被注入到組件的查詢 |
selector | string |
設置用於在模板中識別該組件的css選擇器(組件的自定義標籤) |
如下幾種元數據的等價寫法會比元數據設置更簡潔易懂,因此通常推薦的是等價寫法。
@Component({ selector: 'demo-component', inputs: ['param'] }) export class DemoComponent { param: any; }
等價於:typescript
@Component({ selector: 'demo-component' }) export class DemoComponent { @Input() param: any; }
@Component({ selector: 'demo-component', outputs: ['ready'] }) export class DemoComponent { ready = new eventEmitter<false>(); }
等價於:app
@Component({ selector: 'demo-component' }) export class DemoComponent { @Output() ready = new eventEmitter<false>(); }
@Component({ selector: 'demo-component', host: { '(click)': 'onClick($event.target)', // 事件 'role': 'nav', // 屬性 '[class.pressed]': 'isPressed', // 類 } }) export class DemoComponent { isPressed: boolean = true; onClick(elem: HTMLElement) { console.log(elem); } }
等價於:ide
@Component({ selector: 'demo-component' }) export class DemoComponent { @HostBinding('attr.role') role = 'nav'; @HostBinding('class.pressed') isPressed: boolean = true; @HostListener('click', ['$event.target']) onClick(elem: HTMLElement) { console.log(elem); } }
@Component({ selector: 'demo-component', template: ` <input #theInput type='text' /> <div>Demo Component</div> `, queries: { theInput: new ViewChild('theInput') } }) export class DemoComponent { theInput: ElementRef; }
等價於:函數
@Component({ selector: 'demo-component', template: ` <input #theInput type='text' /> <div>Demo Component</div> ` }) export class DemoComponent { @ViewChild('theInput') theInput: ElementRef; }
<my-list> <li *ngFor="let item of items;">{{item}}</li> </my-list>
@Directive({ selector: 'li' }) export class ListItem {}
@Component({ selector: 'my-list', template: ` <ul> <ng-content></ng-content> </ul> `, queries: { items: new ContentChild(ListItem) } }) export class MyListComponent { items: QueryList<ListItem>; }
等價於:
@Component({ selector: 'my-list', template: ` <ul> <ng-content></ng-content> </ul> ` }) export class MyListComponent { @ContentChild(ListItem) items: QueryList<ListItem>; }
@Input
修飾的變量)的值是否發生變化,當這個值爲引用類型(Object,Array等)時,則只對比該值的引用。當Angular使用構造函數新建組件後,就會按下面的順序在特定時刻調用這些生命週期鉤子方法:
生命週期鉤子 | 調用時機 |
---|---|
ngOnChanges | 在ngOnInit以前調用,或者當組件輸入數據(經過@Input 裝飾器顯式指定的那些變量)變化時調用。 |
ngOnInit | 第一次ngOnChanges以後調用。建議此時獲取數據,不要在構造函數中獲取。 |
ngDoCheck | 每次變化監測發生時被調用。 |
ngAfterContentInit | 使用<ng-content>將外部內容嵌入到組件視圖後被調用,第一次ngDoCheck以後調用且只執行一次(只適用組件)。 |
ngAfterContentChecked | ngAfterContentInit後被調用,或者每次變化監測發生時被調用(只適用組件)。 |
ngAfterViewInit | 建立了組件的視圖及其子視圖以後被調用(只適用組件)。 |
ngAfterViewChecked | ngAfterViewInit,或者每次子組件變化監測時被調用(只適用組件)。 |
ngOnDestroy | 銷燬指令/組件以前觸發。此時應將不會被垃圾回收器自動回收的資源(好比已訂閱的觀察者事件、綁定過的DOM事件、經過setTimeout或setInterval設置過的計時器等等)手動銷燬掉。 |