网站建设资讯

NEWS

网站建设资讯

浅析Angular实现一个repeat指令的方法-创新互联

在项目中常常会使用 ngFor指令,之前只会使用它,具体如何实现的却不得而知。终于这几天有时间"研究"了下它是如何实现的,顺便自己写个简单的 ngFor指令:repeat

专业领域包括网站建设、成都网站设计、商城网站制作、微信营销、系统平台开发, 与其他网站设计及系统开发公司不同,创新互联的整合解决方案结合了帮做网络品牌建设经验和互联网整合营销的理念,并将策略和执行紧密结合,为客户提供全网互联网整合方案。

说到指令就不得不提一下TemplateRef和ViewContainerRef

TemplateRef 可以理解为dom渲染模板,指令通过TemplateRef的模板来创建dom元素
ViewContainerRef 可以理解为TemplateRef的容器,在调用ViewContainerRef上的createEmbeddedView时,传入TemplateRef和context就能创建出dom元素 此外还需要说明的是Angular的微语法,详见下图。


Angular会把微语法展开成ng-template的形式,支持传入参数, TemplateRef
所关联的则是ng-template内的内容,let variable则是声明变量,如果后面没有赋值操作,则这个变量取默认值。这里取值和createEmbeddedView方法的context相关(后面会细说)。

代码示例:

import { Directive, Input, TemplateRef, ViewContainerRef } from "@angular/core";
@Directive({
 selector: "[appRepeat]"
})
export class RepeatDirective {
 constructor(private tpl: TemplateRef, private vc: ViewContainerRef) {}
 @Input() set appRepeatIn(val: Array) {
  val.forEach((item, index) => {
   this.vc.createEmbeddedView(this.tpl, {
    $implicit: item,
    index: index,
    even: index % 2 === 0,
    odd: index % 2 === 1
   });
  });
 }
}
    • index: {{ index }}
    • item: {{ item }}
    • default: {{ defualt }}
    • even: {{ even }}
    • odd: {{ odd }}

分享题目:浅析Angular实现一个repeat指令的方法-创新互联
转载来于:http://cdweb.net/article/gsiej.html