Skip to content

Instantly share code, notes, and snippets.

@davcs86
Last active January 13, 2018 11:13
Show Gist options
  • Save davcs86/1910b096449211876e877c67b20c7215 to your computer and use it in GitHub Desktop.
Save davcs86/1910b096449211876e877c67b20c7215 to your computer and use it in GitHub Desktop.
Load dynamic html content in angular 2/4
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