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