Created
September 25, 2016 08:35
-
-
Save HerringtonDarkholme/0747ed7d67dc7c387a69c094dce9b5b8 to your computer and use it in GitHub Desktop.
Nested For implementation in Angular2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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