Angular2學習教程之TemplateRef和ViewContainerRef詳解
TemplateRef
在介紹 TemplateRef 前,我們先來了解一下 HTML 模板元素 - <template> 。模板元素是一種機制,允許包含加載頁面時不渲染,但又可以隨后通過 JavaScript 進行實例化的客戶端內(nèi)容。我們可以將模板視作為存儲在頁面上稍后使用的一小段內(nèi)容。
在 HTML5 標準引入 template 模板元素之前,我們都是使用 <script> 標簽進行客戶端模板的定義,具體如下:
<script id="tpl-mock" type="text/template"> <span>I am span in mock template</span> </script>
對于支持 HTML5 template 模板元素的瀏覽器,我們可以這樣創(chuàng)建客戶端模板:
<template id="tpl"> <span>I am span in template</span> </template>
下面我們來看一下 HTML5 template 模板元素的使用示例:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"> <title>HTML5 Template Element Demo</title></head> <body> <h4>HTML5 Template Element Demo</h4> <!-- Template Container --> <div class="tpl-container"></div> <!-- Template --> <template id="tpl"> <span>I am span in template</span> </template> <!-- Script --> <script type="text/javascript"> (function renderTpl() { if ('content' in document.createElement('template')) { var tpl = document.querySelector('#tpl'); var tplContainer = document.querySelector('.tpl-container'); var tplNode = document.importNode(tpl.content, true); tplContainer.appendChild(tplNode); } else { throw new Error("Current browser doesn't support template element"); } })(); </script> </body> </html>
以上代碼運行后,在瀏覽器中我們會看到以下內(nèi)容:
HTML5 Template Element Demo I am span in template
而當我們注釋掉 tplContainer.appendChild(tplNode)
語句時,刷新瀏覽器后看到的是:
HTML5 Template Element Demo
這說明頁面中 <template> 模板元素中的內(nèi)容,如果沒有進行處理對用戶來說是不可見的。Angular 2 中,<template> 模板元素主要應用在結(jié)構(gòu)指令中,接下來我們先來介紹一下本文中的第一個主角 - TemplateRef:
import {Component, TemplateRef, ViewChild, AfterViewInit} from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Welcome to Angular World</h1> <template #tpl> <span>I am span in template</span> </template> `, }) export class AppComponent { name: string = 'Semlinker'; @ViewChild('tpl') tpl: TemplateRef<any>; ngAfterViewInit() { console.dir(this.tpl); } }
上述代碼運行后的控制臺的輸出結(jié)果如下:
從上圖中,我們發(fā)現(xiàn) @Component template 中定義的 <template> 模板元素,渲染后被替換成 comment 元素,其內(nèi)容為 "template bindings={}"
。此外我們通過 @ViewChild 獲取的模板元素,是 TemplateRef_ 類的實例,接下來我們來研究一下 TemplateRef_ 類:
TemplateRef_
// @angular/core/src/linker/template_ref.d.ts export declare class TemplateRef_<C> extends TemplateRef<C> { private _parentView; private _nodeIndex; private _nativeElement; constructor(_parentView: AppView<any>, _nodeIndex: number, _nativeElement: any); createEmbeddedView(context: C): EmbeddedViewRef<C>; elementRef: ElementRef; }
TemplateRef
// @angular/core/src/linker/template_ref.d.ts // 用于表示內(nèi)嵌的template模板,能夠用于創(chuàng)建內(nèi)嵌視圖(Embedded Views) export declare abstract class TemplateRef<C> { elementRef: ElementRef; abstract createEmbeddedView(context: C): EmbeddedViewRef<C>; }
(備注:抽象類與普通類的區(qū)別是抽象類有包含抽象方法,不能直接實例化抽象類,只能實例化該抽象類的子類)
我們已經(jīng)知道 <template> 模板元素,渲染后被替換成 comment 元素,那么應該如何顯示我們模板中定義的內(nèi)容呢 ?我們注意到了 TemplateRef 抽象類中定義的 createEmbeddedView抽象方法,該方法的返回值是 EmbeddedViewRef 對象。那好我們馬上來試一下:
import {Component, TemplateRef, ViewChild, AfterViewInit} from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Welcome to Angular World</h1> <template #tpl> <span>I am span in template</span> </template> `, }) export class AppComponent { name: string = 'Semlinker'; @ViewChild('tpl') tpl: TemplateRef<any>; ngAfterViewInit() { let embeddedView = this.tpl.createEmbeddedView(null); console.dir(embeddedView); } }
上述代碼運行后的控制臺的輸出結(jié)果如下:
從圖中我們可以知道,當調(diào)用 createEmbeddedView 方法后返回了 ViewRef_ 視圖對象。該視圖對象的 rootNodes 屬性包含了 <template> 模板中的內(nèi)容。在上面的例子中,我們知道了 TemplateRef 實例對象中的 elementRef 屬性封裝了我們的 comment 元素,那么我們可以通過 insertBefore 方法來創(chuàng)建我們模板中定義的內(nèi)容。
import { Component, TemplateRef, ViewChild, AfterViewInit } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Welcome to Angular World</h1> <template #tpl> <span>I am span in template {{name}}</span> </template> `, }) export class AppComponent { name: string = 'Semlinker'; @ViewChild('tpl') tpl: TemplateRef<any>; ngAfterViewInit() { // 頁面中的<!--template bindings={}-->元素 let commentElement = this.tpl.elementRef.nativeElement; // 創(chuàng)建內(nèi)嵌視圖 let embeddedView = this.tpl.createEmbeddedView(null); // 動態(tài)添加子節(jié)點 embeddedView.rootNodes.forEach((node) => { commentElement.parentNode .insertBefore(node, commentElement.nextSibling); }); } }
成功運行上面的代碼后,在瀏覽器中我們會看到以下內(nèi)容:
Welcome to Angular World I am span in template
現(xiàn)在我們來回顧一下,上面的處理步驟:
- 創(chuàng)建內(nèi)嵌視圖(embedded view)
- 遍歷內(nèi)嵌視圖中的 rootNodes,動態(tài)的插入 node
雖然我們已經(jīng)成功的顯示出 template 模板元素中的內(nèi)容,但發(fā)現(xiàn)整個流程還是太復雜了,那有沒有簡單地方式呢 ?是時候介紹本文中第二個主角 - ViewContainerRef。
ViewContainerRef
我們先來檢驗一下它的能力,然后再來好好地分析它。具體示例如下:
import { Component, TemplateRef, ViewChild, ViewContainerRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Welcome to Angular World</h1> <template #tpl> <span>I am span in template</span> </template> `, }) export class AppComponent { name: string = 'Semlinker'; @ViewChild('tpl') tplRef: TemplateRef<any>; @ViewChild('tpl', { read: ViewContainerRef }) tplVcRef: ViewContainerRef; ngAfterViewInit() { // console.dir(this.tplVcRef); (1) this.tplVcRef.createEmbeddedView(this.tplRef); } }
移除上面代碼中的注釋,即可在控制臺看到以下的輸出信息:
而在瀏覽器中我們會看到以下內(nèi)容:
Welcome to Angular World I am span in template
接下來我們來看一下 ViewContainerRef_ 類:
// @angular/core/src/linker/view_container_ref.d.ts // 用于表示一個視圖容器,可添加一個或多個視圖 export declare class ViewContainerRef_ implements ViewContainerRef { ... length: number; // 返回視圖容器中已存在的視圖個數(shù) element: ElementRef; injector: Injector; parentInjector: Injector; // 基于TemplateRef創(chuàng)建內(nèi)嵌視圖,并自動添加到視圖容器中,可通過index設(shè)置 // 視圖添加的位置 createEmbeddedView<C>(templateRef: TemplateRef<C>, context?: C, index?: number): EmbeddedViewRef<C>; // 基 ComponentFactory創(chuàng)建組件視圖 createComponent<C>(componentFactory: ComponentFactory<C>, index?: number, injector?: Injector, projectableNodes?: any[][]): ComponentRef<C>; insert(viewRef: ViewRef, index?: number): ViewRef; move(viewRef: ViewRef, currentIndex: number): ViewRef; indexOf(viewRef: ViewRef): number; remove(index?: number): void; detach(index?: number): ViewRef; clear(): void; }
通過源碼我們可以知道通過 ViewContainerRef_ 實例,我們可以方便地操作視圖,也可以方便地基于 TemplateRef 創(chuàng)建視圖。現(xiàn)在我們來總結(jié)一下 TemplateRef 與 ViewContainerRef。
TemplateRef:用于表示內(nèi)嵌的 template 模板元素,通過 TemplateRef 實例,我們可以方便創(chuàng)建內(nèi)嵌視圖(Embedded Views),且可以輕松地訪問到通過 ElementRef 封裝后的 nativeElement。需要注意的是組件視圖中的 template 模板元素,經(jīng)過渲染后會被替換成 comment 元素。
ViewContainerRef:用于表示一個視圖容器,可添加一個或多個視圖。通過 ViewContainerRef 實例,我們可以基于 TemplateRef 實例創(chuàng)建內(nèi)嵌視圖,并能指定內(nèi)嵌視圖的插入位置,也可以方便對視圖容器中已有的視圖進行管理。簡而言之,ViewContainerRef 的主要作用是創(chuàng)建和管理內(nèi)嵌視圖或組件視圖。
我有話說
1.Angular 2 支持的 View(視圖) 類型有哪幾種 ?
- Embedded Views - Template 模板元素
- Host Views - Component 組件
1.1 如何創(chuàng)建 Embedded View
ngAfterViewInit() { let view = this.tpl.createEmbeddedView(null); }
1.2 如何創(chuàng)建 Host View
constructor(private injector: Injector, private r: ComponentFactoryResolver) { let factory = this.r.resolveComponentFactory(AppComponent); let componentRef = factory.create(injector); let view = componentRef.hostView; }
2.Angular 2 Component 組件中定義的 <template> 模板元素為什么渲染后會被移除 ?
因為 <template> 模板元素,已經(jīng)被 Angular 2 解析并封裝成 TemplateRef 實例,通過 TemplateRef 實例,我們可以方便地創(chuàng)建內(nèi)嵌視圖(Embedded View),我們不需要像開篇中的例子那樣,手動操作 <template> 模板元素。
3.ViewRef 與 EmbeddedViewRef 之間有什么關(guān)系 ?
ViewRef 用于表示 Angular View(視圖),視圖是可視化的 UI 界面。EmbeddedViewRef 繼承于 ViewRef,用于表示 <template> 模板元素中定義的 UI 元素。
ViewRef
// @angular/core/src/linker/view_ref.d.ts export declare abstract class ViewRef { destroyed: boolean; abstract onDestroy(callback: Function): any; }
EmbeddedViewRef
// @angular/core/src/linker/view_ref.d.ts export declare abstract class EmbeddedViewRef<C> extends ViewRef { context: C; rootNodes: any[]; // 保存<template>模板中定義的元素 abstract destroy(): void; // 用于銷毀視圖 }
總結(jié)
Angular 2 中 TemplateRef 與 ViewContainerRef 的概念對于初學者來說會比較羞澀難懂,本文從基本的 HTML 5 <template> 模板元素開始,介紹了如何操作和應用頁面中定義的模板。然后通過實例介紹了 Angular 2 中 TemplateRef 和 ViewContainerRef 的定義和作用。希望通過這篇文章,讀者能更好的理解 TemplateRef 與 ViewContainerRef。
好了,以上就是這篇文章的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
AngularJS基礎(chǔ) ng-paste 指令簡單示例
本文主要介紹AngularJS ng-paste 指令,這里對ng-paste 指令的基礎(chǔ)資料做了整理,并附有代碼示例,有需要的朋友可以參考下2016-08-08利用Angularjs和原生JS分別實現(xiàn)動態(tài)效果的輸入框
現(xiàn)在的很多網(wǎng)站都將輸入框做成了動態(tài)的效果,這樣對于用戶體檢來說非常好,這篇文章分別用Angularjs和原生JS兩種方法來實現(xiàn)動態(tài)效果的輸入框,具有一定的參考價值,有需要的小伙伴們可以來參考借鑒。2016-09-09AngularJS基于ui-route實現(xiàn)深層路由的方法【路由嵌套】
這篇文章主要介紹了AngularJS基于ui-route實現(xiàn)深層路由的方法,涉及AngularJS路由嵌套操作相關(guān)實現(xiàn)步驟與技巧,需要的朋友可以參考下2016-12-12AngularJS全局scope與Isolate scope通信用法示例
這篇文章主要介紹了AngularJS全局scope與Isolate scope通信用法,結(jié)合格式分析了全局scope和directive本地scope相關(guān)功能、通信用法與相關(guān)注意事項,需要的朋友可以參考下2016-11-11