In this post, we are going to create our own structure directive *ngFor.

What it should looks like in HTML?

    <div>
<ul>
<li *myFor="let item of items; let i = index;">
{{ i }} Member: {{ item.name | json }}
</li>
<template myFor [myForOf]="items" let-item let-i="index">
<li>{{ i }} Member: {{ item.name | json }}</li>
</template>
</ul>
</div>

So here, we have a '*myFor' directive. It also use 'myForOf' direcitve. And a implicit value 'item'.

Notice that:

        <li *myFor="let item of items; let i = index;">
{{ i }} Member: {{ item.name | json }}
</li>

and

        <template myFor [myForOf]="items" let-item let-i="index">
<li>{{ i }} Member: {{ item.name | json }}</li>
</template>

They have the same effect.

Now let's create myFor directive:

import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';

@Directive({
selector: '[myFor][myForOf]'
})
export class MyForDirective {
@Input()
set myForOf(collection) {
this.view.clear();
collection.forEach((item, index) => {
this.view.createEmbeddedView(
this.template,
{
$implicit: item,
index
}
)
});
} constructor(
private view: ViewContainerRef,
private template: TemplateRef<any>
) {
// this.template will point to the host element
}
}

It is good to clear the view every time we generate new embedded view:

this.view.clear();

Also we gave implicit 'value' and 'index'.

      this.view.createEmbeddedView(
this.template,
{
$implicit: item, // let-item
index // let-i="index"
}
)

最新文章

  1. 【腾讯GAD暑期训练营游戏程序班】游戏场景管理作业说明文档
  2. C# 计算一段代码执行的时间函数
  3. Frequent values &amp;&amp; Ping pong
  4. (转载)php反射类 ReflectionClass
  5. Java was started but returned exit code=13
  6. COJ 1010 WZJ的数据结构(十) 线段树区间操作
  7. 【hihoCoder第十四周】无间道之并查集
  8. 【LeetCode练习题】Linked List Cycle II
  9. TypeScript 学习四 面向对象的特性,泛型,接口,模块,类型定义文件*.d.ts
  10. android studio的lib和jniLibs
  11. WCF Restful调用跨域解决方案
  12. LeetCode(47)-Reverse Bits
  13. MySQL 5.7 忘记密码
  14. JS与CSS阻止元素被选中及清除选中的方法总结
  15. 判断Excel版本信息
  16. Node remains in conflict,svn冲突解决办法
  17. 文件IO(2)
  18. Mycat配置入门
  19. java基础面试题(JVM篇)
  20. IIS7的网站通过https访问提示ssl_error_rx_record_too_long

热门文章

  1. 囧 appspot.com/
  2. Redis-消费模式
  3. 【Codeforces Round #447 (Div. 2) C】Marco and GCD Sequence
  4. java线程——三种创建线程的方式
  5. poj 1191 棋盘切割 (压缩dp+记忆化搜索)
  6. Android 监听电量的状态
  7. arduino串口输出问题
  8. 硬件——STM32 , 软件框架
  9. JS学习笔记 - 面向对象 - 原型
  10. 四种卸载Mac软件的方法