欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

angular之ng-template模板加载

程序员文章站 2022-06-24 15:57:56
本文介绍了angular之ng-template模板加载,分享给大家,具体如下: html5中的template template标签的含义:html

本文介绍了angular之ng-template模板加载,分享给大家,具体如下:

html5中的template

template标签的含义:html <template>元素是一种用于保存客户端内容的机制,该内容在页面加载时是不可见的,但可以在运行时使用javascript进行实例化,可以将一个模板视为正在被存储以供随后在文档中使用的一个内容片段。

angular之ng-template模板加载

属性

此元素仅包含全局属性和只读的 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为例:

angular之ng-template模板加载

<ng-template> 模板元素与html5的template元素一样,需要被特殊处理后才能渲染。ng主要是通过类templateref和viewcontainerref实现的。

通过阅读ngif源码学习如何运用<ng-template>

在使用ngif 指令时我们并未发现ng-template的身影,这是因为"*"(星号)语法糖的原因,这个简写方法是一个微语法,而不是通常的模板表达式, angular会解开这个语法糖,变成一个<ng-template>标记,包裹着宿主元素及其子元素。

<div *ngif="hero" >{{hero.name}}</div>

会被解析为

<ng-template [ngif]="hero">
 <div>{{hero.name}}</div>
</ng-template>`

看下ngif源码

import {directive, embeddedviewref, input, templateref, viewcontainerref} from '@angular/core';
@directive({selector: '[ngif]'})
export class ngif {
 private _context: ngifcontext = new ngifcontext();
 private _thentemplateref: templateref<ngifcontext>|null = null;
 private _elsetemplateref: templateref<ngifcontext>|null = null;
 private _thenviewref: embeddedviewref<ngifcontext>|null = null;
 private _elseviewref: embeddedviewref<ngifcontext>|null = null;

 constructor(private _viewcontainer: viewcontainerref, templateref: templateref<ngifcontext>) {
  this._thentemplateref = templateref;
 }

 @input()
 set ngif(condition: any) {
  this._context.$implicit = this._context.ngif = condition;
  this._updateview();
 }

 @input()
 set ngifthen(templateref: templateref<ngifcontext>) {
  this._thentemplateref = templateref;
  this._thenviewref = null; // clear previous view if any.
  this._updateview();
 }

 @input()
 set ngifelse(templateref: templateref<ngifcontext>) {
  this._elsetemplateref = templateref;
  this._elseviewref = null; // clear previous view if any.
  this._updateview();
 }

 private _updateview() {
  if (this._context.$implicit) {
   if (!this._thenviewref) {
    this._viewcontainer.clear();
    this._elseviewref = null;
    if (this._thentemplateref) {
     this._thenviewref =
       this._viewcontainer.createembeddedview(this._thentemplateref, this._context);
    }
   }
  } else {
   if (!this._elseviewref) {
    this._viewcontainer.clear();
    this._thenviewref = null;
    if (this._elsetemplateref) {
     this._elseviewref =
       this._viewcontainer.createembeddedview(this._elsetemplateref, this._context);
    }
   }
  }
 }
}

export class ngifcontext {
 public $implicit: any = null;
 public ngif: any = null;
}

ngif的源码并不难,它的核心就在于_updateview函数,它主要通过viewcontainerref的createembeddedview和clear方法来实现模板templateref的呈现和清除(先不关注当中的then和else等的具体实现)。它使用templateref取得<ng-template>的内容,并通过viewcontainerref来访问这个视图容器。

templateref

templateref 实例用于表示模板对象,templateref 抽象类的定义如下:

 abstract get elementref(): elementref;
 abstract createembeddedview(context: c): embeddedviewref<c>;
}

在指令中通过依赖注入templateref可以直接拿到ng-tempalte的templateref,但是在component组件中我们则需要使用viewchild

<ng-template #tptest>
 <span>template test</span>
</ng-template>

@viewchild('tptest') tptest: templateref<any>;

viewcontainerref

viewcontainerref 实例提供了 createembeddedview() 方法,该方法接收 templateref 对象作为参数,并将模板中的内容作为容器 (comment 元素) 的兄弟元素,插入到页面中。

export abstract class viewcontainerref {
  /*基于templateref对象创建embedded view(内嵌视图),然后根据`index`指定的值,插入到容器中。 
  如果没有指定`index`的值,新创建的视图将作为容器中的最后一个视图插入。*/ 
 abstract createembeddedview<c>(
   templateref: templateref<c>, //内嵌视图
   context?: c, index?: number): // 创建上下文
   embeddedviewref<c>;
}

createembeddedview:context

创建template 自身 context 的属性,以ngfor为例:
查看ngfor context源码:

export class ngforofcontext<t> {
 constructor(
   public $implicit: t, public ngforof: ngiterable<t>, public index: number,
   public count: number) {}

 get first(): boolean { return this.index === 0; }

 get last(): boolean { return this.index === this.count - 1; }

 get even(): boolean { return this.index % 2 === 0; }

 get odd(): boolean { return !this.even; }
}

<div *ngfor="let hero of heroes; let i=index; let odd=odd">
 ({{i}}) {{hero.name}}
</div>


解析后:

<ng-template ngfor let-hero [ngforof]="heroes" let-i="index" let-odd="odd" >
 <div>({{i}}) {{hero.name}}</div>
</ng-template>

从例子中可以看到,通过let-i let-odd可以获取到template的context,这是angular提供的一种语法。因为在 angular中是没有作用域继承的,所以在模版中无法隐式实现两个无关数据源。一个简单的实现方案就是:一个显式、一个隐式。由于ng-template tag 是写在某个 component 的 template属性中的,所以在 ng-template tag 之下的部分当然能访问的也只有 component 作为 context 提供的属性,从而保持行为的一致性,而如果需要访问到 template 的 context,我们就需要使用额外的引入语法。比如 let-i="index",就是把 template context 中的 index属性引入到当前的 component context 中并赋予别名 i,这样,我们就能够使用 i 这个标识符来访问到 template context 中的属性了,并且仍然保持了行为的一致性和作用域的独立性。

模板输入变量是这样一种变量,你可以在单个实例的模板中引用它的值。 这个例子中有好几个模板输入变量:hero、i和odd。 它们都是用let作为前导关键字。

模板输入变量和模板引用变量是不同的,无论是在语义上还是语法上。

我们使用let关键字(如let hero)在模板中声明一个模板输入变量。 这个变量的范围被限制在所重复模板的单一实例上。
而声明模板引用变量使用的是给变量名加#前缀的方式(#var)。 一个引用变量引用的是它所附着到的元素、组件或指令。它可以在整个模板任意位置**访问。

模板输入变量和引用变量具有各自独立的命名空间。let hero中的hero和#hero中的hero并不是同一个变量。

总结:

<ng-template>在ng中主要通过viewchild templateref viewcontainerref来实现结构性操作。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。