Last active
January 13, 2018 11:13
-
-
Save davcs86/1910b096449211876e877c67b20c7215 to your computer and use it in GitHub Desktop.
Load dynamic html content in angular 2/4
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 { | |
Compiler, Component, ComponentFactory, ComponentRef, Injector, NgModule, NgModuleRef, ViewChild, | |
ViewContainerRef | |
} from '@angular/core'; | |
import {TemplateService} from "../../services/template/template.service"; | |
import {ReactiveFormsModule} from "@angular/forms"; | |
@Component({ | |
selector: 'base-component', | |
template: '<div #child></div>' | |
}) | |
export class BaseComponent { | |
// reference for html element with #child tag | |
@ViewChild('child', {read: ViewContainerRef}) protected child: ViewContainerRef; | |
constructor(private _compiler: Compiler, private _injector: Injector, | |
private _m: NgModuleRef<any>, private templateService: TemplateService) { | |
} | |
getAllFuncs(obj: any): Array<string> { | |
let props: Array<string> = []; | |
do { | |
props = props.concat(Object.getOwnPropertyNames(obj)); | |
} while (obj = Object.getPrototypeOf(obj)); | |
return props.sort().filter(function (e, i, arr) { | |
//console.log(e, i, arr); | |
if (e == 'constructor' || | |
e == 'getAllFuncs' || | |
e == 'hasOwnProperty' || | |
e == 'isPrototypeOf' || | |
e == 'propertyIsEnumerable' || | |
e == 'toLocaleString' || | |
e == 'toString' || | |
e == 'valueOf' || | |
e.startsWith('__')) return false; | |
if (e != arr[i + 1]) return true; | |
}); | |
} | |
/* | |
templateService.loadHTML basically is a Http.get() with some custom headers | |
*/ | |
ngAfterViewInit() { | |
this.templateService.loadHTML('/template/contactds').subscribe(resp => { | |
const templateContent = resp.text(); | |
const tmpCmp = Component({template: templateContent})(class { | |
}); | |
const tmpModule = NgModule({ | |
declarations: [ | |
tmpCmp | |
], | |
imports: [ | |
ReactiveFormsModule | |
] | |
})(class {/* */ }); | |
this._compiler.compileModuleAndAllComponentsAsync(tmpModule) | |
.then((factories) => { | |
const f = factories.componentFactories[0]; | |
const cmpRef = f.create(this._injector, [], null, this._m); | |
const funcs = this.getAllFuncs(this); | |
funcs.forEach(f => { | |
cmpRef.instance[f] = (this as any)[f]; | |
}); | |
this.child.insert(cmpRef.hostView); | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment