Skip to content

Instantly share code, notes, and snippets.

@HerringtonDarkholme
Created September 25, 2016 08:35
Show Gist options
  • Save HerringtonDarkholme/0747ed7d67dc7c387a69c094dce9b5b8 to your computer and use it in GitHub Desktop.
Save HerringtonDarkholme/0747ed7d67dc7c387a69c094dce9b5b8 to your computer and use it in GitHub Desktop.
Nested For implementation in Angular2
import {
Component, NgModule, TemplateRef,
Directive, Input, ViewContainerRef,
Compiler, OnChanges, ComponentFactory
} from '@angular/core'
import { CommonModule } from '@angular/common'
@Component({
template: `
<template ngFor let-sub [ngForOf]="arr">
<template [ngTemplateOutlet]="templateRef" *ngFor="let a of sub" [ngOutletContext]="{$implicit: a}"></template>
</template>
`
})
export class NestedForImpl {
arr: Array<any>
templateRef: TemplateRef<any>
ngOnInit() {}
}
@Directive({ selector: '[nestedFor][nestedForOf]' })
export class NestedFor implements OnChanges {
@Input() nestedForOf: any[][]
private componentFactory: ComponentFactory<NestedForImpl>
constructor(
private templateRef: TemplateRef<any>,
private compiler: Compiler,
private vcRef: ViewContainerRef
) {
let module = this.compiler.compileModuleAndAllComponentsSync(NestedForModule)
this.componentFactory = module.componentFactories.find(f => f.componentType === NestedForImpl)
}
ngOnChanges() {
let componentRef = this.vcRef.createComponent(this.componentFactory, 0)
componentRef.instance.templateRef = this.templateRef
componentRef.instance.arr = this.nestedForOf
componentRef.changeDetectorRef.detectChanges()
}
}
@NgModule({
imports: [CommonModule],
exports: [NestedFor],
declarations: [NestedFor, NestedForImpl]
})
export class NestedForModule {}
import { Component } from '@angular/core'
@Component({
selector: 'my-app',
template: `
<h1 *nestedFor="let a of nested">Hello {{a}}</h1>
`,
})
export class AppComponent {
nested = [[1,2,3], [4,5,6]]
ngOnInit() {
setTimeout(() => {
this.nested.push([2, 3, 3])
}, 1000)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment