使用带有索引的自定义结构指令:
根据Angular文档:
createEmbeddedView
实例化一个嵌入式视图,并将其插入此容器。
abstract createEmbeddedView(templateRef: TemplateRef, context?: C, index?: number): EmbeddedViewRef
。
Param Type Description
templateRef TemplateRef the HTML template that defines the view.
context C optional. Default is undefined.
index number the 0-based index at which to insert the new view into this container. If not specified, appends the new view as the last entry.
当angular通过调用createEmbeddedView创建模板时,它也可以传递将在内部使用的上下文ng-template
。
使用context可选参数,您可以在组件中使用它,就像使用* ngFor一样在模板中提取它。
app.component.html:
<p *for="number; let i=index; let c=length; let f=first; let l=last; let e=even; let o=odd">
item : {{i}} / {{c}}
<b>
{{f ? "First,": ""}}
{{l? "Last,": ""}}
{{e? "Even." : ""}}
{{o? "Odd." : ""}}
</b>
</p>
指令:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
class Context {
constructor(public index: number, public length: number) { }
get even(): boolean { return this.index % 2 === 0; }
get odd(): boolean { return this.index % 2 === 1; }
get first(): boolean { return this.index === 0; }
get last(): boolean { return this.index === this.length - 1; }
}
@Directive({
selector: '[for]'
})
export class ForDirective {
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { }
@Input('for') set loop(num: number) {
for (var i = 0; i < num; i++)
this.viewContainer.createEmbeddedView(this.templateRef, new Context(i, num));
}
}