本文介绍了angular之ng-template模板加载,分享给大家,具体如下:
html5中的template
template标签的含义:HTML <template>元素是一种用于保存客户端内容的机制,该内容在页面加载时是不可见的,但可以在运行时使用JavaScript进行实例化,可以将一个模板视为正在被存储以供随后在文档中使用的一个内容片段。

属性
此元素仅包含全局属性和只读的 content 属性,通过content 可以读取模板内容,而且可以通过判断 content 属性是否存在来判断浏览器是否支持 <template> 元素。
示例
html
<table id="producttable"> <thead> <tr> <td>UPC_Code</td> <td>Product_Name</td> </tr> </thead> <tbody> <!-- 现有数据可以可选地包括在这里 --> </tbody> </table> <template id="productrow"> <tr> <td class="record"></td> <td></td> </tr> </template>
js
// 通过检查来测试浏览器是否支持HTML模板元素
// 用于保存模板元素的内容属性。
if ('content' in document.createElement('template')) {
// 使用现有的HTML tbody实例化表和该行与模板
let t = document.querySelector('#productrow'),
td = t.content.querySelectorAll("td");
td[0].textContent = "1235646565";
td[1].textContent = "Stuff";
// 克隆新行并将其插入表中
let tb = document.getElementsByTagName("tbody");
let clone = document.importNode(t.content, true);
tb[0].appendChild(clone);
// 创建一个新行
td[0].textContent = "0384928528";
td[1].textContent = "Acme Kidney Beans";
// 克隆新行并将其插入表中
let clone2 = document.importNode(t.content, true);
tb[0].appendChild(clone2);
} else {
// 找到另一种方法来添加行到表,因为不支持HTML模板元素。
}
代码运行后,结果将是一个包含(由 JavaScript 生成)两个新行的 HTML 表格:
UPC_Code Product_Name 1235646565 Stuff 0384928528 Acme Kidney Beans
注释掉 tb[0].appendChild(clone);和tb[0].appendChild(clone2);,运行代码,只会看到:
UPC_Code Product_Name
说明template元素中的内容如果不经过处理,浏览器是不会渲染的。
angular中的ng-template
<ng-template>是一个 Angular 元素,它永远不会直接显示出来。在渲染视图之前,Angular 会把<ng-template>及其内容替换为一个注释。
以ngIf为例:
