最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

剖析Angular Component的源碼示例

 更新時間:2018年03月23日 09:24:32   作者:laixiangran  
本篇文章主要介紹了剖析Angular Component的源碼示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

Web Component

在介紹Angular Component之前,我們先簡單了解下W3C Web Components

定義

W3C為統(tǒng)一組件化標準方式,提出Web Component的標準。

每個組件包含自己的html、css、js代碼。
Web Component標準包括以下四個重要的概念:
1.Custom Elements(自定義標簽):可以創(chuàng)建自定義 HTML 標記和元素;
2.HTML Templates(HTML模版):使用 <template> 標簽去預定義一些內容,但并不加載至頁面,而是使用 JS 代碼去初始化它;
3.Shadow DOM(虛擬DOM):可以創(chuàng)建完全獨立與其他元素的DOM子樹;
4.HTML Imports(HTML導入):一種在 HTML 文檔中引入其他 HTML 文檔的方法,<link rel="import" href="example.html" rel="external nofollow" />。

概括來說就是,可以創(chuàng)建自定義標簽來引入組件是前端組件化的基礎,在頁面引用 HTML 文件和 HTML 模板是用于支撐編寫組件視圖和組件資源管理,而 Shadow DOM 則是隔離組件間代碼的沖突和影響。

示例

定義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');

  // 創(chuàng)建一個新元素的原型,繼承自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-component

<!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" rel="external nofollow" >
</head>
<body>
  <!--自定義標簽-->
  <hello-component></hello-component>
</body>
</html>

從以上代碼可看到,hello.html 為按標準定義的組件(名稱為 hello-component ),在這個組件中有自己的結構、樣式及邏輯,然后在 index.html 中引入該組件文件,即可像普通標簽一樣使用。

Angular Component

Angular Component屬于指令的一種,可以理解為擁有模板的指令。其它兩種是屬性型指令和結構型指令。

基本組成

@Component({
  selector: 'demo-component',
  template: 'Demo Component'
})
export class DemoComponent {}
  1. 組件裝飾器:每個組件類必須用@component進行裝飾才能成為Angular組件。
  2. 組件元數(shù)據:組件元數(shù)據:selector、template等,下文將著重講解每個元數(shù)據的含義。
  3. 組件類:組件實際上也是一個普通的類,組件的邏輯都在組件類里定義并實現(xiàn)。
  4. 組件模板:每個組件都會關聯(lián)一個模板,這個模板最終會渲染到頁面上,頁面上這個DOM元素就是此組件實例的宿主元素。

組件元數(shù)據

自身元數(shù)據屬性

名稱 類型 作用
animations AnimationEntryMetadata[] 設置組件的動畫
changeDetection ChangeDetectionStrategy 設置組件的變化監(jiān)測策略
encapsulation ViewEncapsulation 設置組件的視圖包裝選項
entryComponents any[] 設置將被動態(tài)插入到該組件視圖中的組件列表
interpolation [string, string] 自定義組件的插值標記,默認是雙大括號
moduleId string 設置該組件在 ES/CommonJS 規(guī)范下的模塊id,它被用于解析模板樣式的相對路徑
styleUrls string[] 設置組件引用的外部樣式文件
styles string[] 設置組件使用的內聯(lián)樣式
template string 設置組件的內聯(lián)模板
templateUrl string 設置組件模板所在路徑
viewProviders Provider[] 設置組件及其所有子組件(不含ContentChildren)可用的服務

從 core/Directive 繼承

名稱 類型 作用
exportAs string 設置組件實例在模板中的別名,使得可以在模板中調用
host {[key: string]: string} 設置組件的事件、動作和屬性等
inputs string[] 設置組件的輸入屬性
outputs string[] 設置組件的輸出屬性
providers Provider[] 設置組件及其所有子組件(含ContentChildren)可用的服務(依賴注入)
queries {[key: string]: any} 設置需要被注入到組件的查詢
selector string 設置用于在模板中識別該組件的css選擇器(組件的自定義標簽)

幾種元數(shù)據詳解

以下幾種元數(shù)據的等價寫法會比元數(shù)據設置更簡潔易懂,所以一般推薦的是等價寫法。

inputs

@Component({
  selector: 'demo-component',
  inputs: ['param']
})
export class DemoComponent {
  param: any;
}

等價于:

@Component({
  selector: 'demo-component'
})
export class DemoComponent {
  @Input() param: any;
}

outputs

@Component({
  selector: 'demo-component',
  outputs: ['ready']
})
export class DemoComponent {
  ready = new eventEmitter<false>();
}

等價于:

@Component({
  selector: 'demo-component'
})
export class DemoComponent {
  @Output() ready = new eventEmitter<false>();
}

host

@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);
  }
}

等價于:

@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);
  }
}

queries - 視圖查詢

@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;
}

queries - 內容查詢

<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>;
}

styleUrls、styles

styleUrls和styles允許同時指定。

優(yōu)先級:模板內聯(lián)樣式 > styleUrls > styles。

建議:使用styleUrls引用外部樣式表文件,這樣代碼結構相比styles更清晰、更易于管理。同理,模板推薦使用templateUrl引用模板文件。

changeDetection

ChangeDetectionStrategy.Default:組件的每次變化監(jiān)測都會檢查其內部的所有數(shù)據(引用對象也會深度遍歷),以此得到前后的數(shù)據變化。

ChangeDetectionStrategy.OnPush:組件的變化監(jiān)測只檢查輸入屬性(即@Input修飾的變量)的值是否發(fā)生變化,當這個值為引用類型(Object,Array等)時,則只對比該值的引用。

顯然,OnPush策略相比Default降低了變化監(jiān)測的復雜度,很好地提升了變化監(jiān)測的性能。如果組件的更新只依賴輸入屬性的值,那么在該組件上使用OnPush策略是一個很好的選擇。

encapsulation

ViewEncapsulation.None:無 Shadow DOM,并且也無樣式包裝。

ViewEncapsulation.Emulated:無 Shadow DOM,但是通過Angular提供的樣式包裝機制來模擬組件的獨立性,使得組件的樣式不受外部影響,這是Angular的默認設置。

ViewEncapsulation.Native:使用原生的 Shadow DOM 特性。

生命周期

當Angular使用構造函數(shù)新建組件后,就會按下面的順序在特定時刻調用這些生命周期鉤子方法:

生命周期鉤子 調用時機
ngOnChanges 在ngOnInit之前調用,或者當組件輸入數(shù)據(通過@Input裝飾器顯式指定的那些變量)變化時調用。
ngOnInit 第一次ngOnChanges之后調用。建議此時獲取數(shù)據,不要在構造函數(shù)中獲取。
ngDoCheck 每次變化監(jiān)測發(fā)生時被調用。
ngAfterContentInit 使用
ngAfterContentChecked ngAfterContentInit后被調用,或者每次變化監(jiān)測發(fā)生時被調用(只適用組件)。
ngAfterViewInit 創(chuàng)建了組件的視圖及其子視圖之后被調用(只適用組件)。
ngAfterViewChecked ngAfterViewInit,或者每次子組件變化監(jiān)測時被調用(只適用組件)。
ngOnDestroy 銷毀指令/組件之前觸發(fā)。此時應將不會被垃圾回收器自動回收的資源(比如已訂閱的觀察者事件、綁定過的DOM事件、通過setTimeout或setInterval設置過的計時器等等)手動銷毀掉。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論

德阳市| 克什克腾旗| 墨玉县| 收藏| 微山县| 教育| 库车县| 华蓥市| 金沙县| 龙游县| 伊春市| 绍兴市| 邯郸县| 都安| 吉木萨尔县| 理塘县| 娄底市| 临海市| 承德县| 来凤县| 大埔县| 汶上县| 华阴市| 河南省| 盈江县| 旬邑县| 福安市| 且末县| 绩溪县| 丹凤县| 汪清县| 永昌县| 武乡县| 江陵县| 韩城市| 张北县| 许昌县| 吉木乃县| 建德市| 时尚| 天祝|