H5之template元素
模版元素是 Web Components 技術中的一種。
里面的元素在頁面加載時不會呈現,在隨后的JS實例化時可以呈現。
<template id="tpl"> <span>so good </span> </template> <div id="container"> </div> <script type="text/javascript"> const container = document.getElementById('container'); const tpl = document.getElementById('tpl'); let tplNode = document.importNode(tpl.content,true); container.appendChild(tplNode); </script>
template 的類型是 HTMLTemplateElement.
模版元素 在 HTMLTemplateElement.content 中, 類型是 DocumentFragment,在瀏覽器渲染出來的結果如下:
<template id="tpl"> #document-fragment <span>so good </span> </template>
DocumentFragment 表示一個沒有父級文件的最小文檔對象,常常被作為一個輕量版的Document使用。
是DOM節點, 不是真實DOM樹的一部分。 在DOM樹中,文檔片段被其所有子元素代替。
因為文檔片段存在內存中,不存在DOM樹中,將元素插入文檔片段時,不會引起回流。
Angular 之 視圖類型
Angular 支持的 View 視圖 類型:
1、Embeded Views - Template 模版元素
2、Host View是 --Componet 組件
Angular 之 TemplateRef
內嵌template模板元素,通過TemplateRef實例,可以通過ElementRef 封裝后的nativeElement。
<ng-template #tpl> <span>I am span in template {{title}}</span> </ng-template> @ViewChild('tpl') tpl: TemplateRef<any>; title:string = 'jack'; ngAfterViewInit() { const embeddedView = this.tpl.createEmbeddedView(null); // 創建內嵌視圖 const commentElement = this.tpl.elementRef.nativeElement; // 模版DOM元素,此時被渲染成了 comment元素
// 遍歷內嵌視圖中的rootNodes, 動態插入 node embeddedView.rootNodes.forEach( (node) => { commentElement.parentNode.insertBefore(node, commentElement.nextSibling); }); }
由上圖可得知如下結論:
1、<ng-template>元素渲染后被替換成 comment元素。
2、通過@ViewChild獲取的模版元素 this.tpl,是 TemplateRef_ 類的實例。
其中 TemplateRef_<C> extends TemplateRef<C> 。
3、內嵌視圖 是 ViewRef_ 對象,其rootNodes屬性包含了<template>模版中的內容。
4、EmbeddedViewRef<C> extends ViewRef 。
Angular 之 ViewContainerRef
上述方法渲染數據,似乎只能渲染靜態文本,而 {{title}} 值卻沒有渲染出來。
這時候就需要 ViewContainerRef。
ViewContainerRef: 視圖容器,用於創建和管理內嵌視圖或組件視圖。
可添加一個或多個基於TemplateRef實例創建內嵌視圖,指定內嵌視圖的插入位置。
<ng-template #tpl1> <span>我是第一個模版</span> </ng-template> <ng-template #tpl2> <span>我是第二個模版</span> </ng-template> @ViewChild('tpl1') tpl1: ElementRef<any>; @ViewChild('tpl2') tpl2: ElementRef<any>; @ViewChild('tpl1', { read: ViewContainerRef } ) tplContainer: ViewContainerRef; ngAfterViewInit() { const view1 = this.tpl1.createEmbeddedView(null); const view2 = this.tpl2.createEmbeddedView(null); this.tplContainer.insert(view1); this.tplContainer.insert(view2); }