Skip to content

Instantly share code, notes, and snippets.

@soyuka
Created January 5, 2022 15:59
Show Gist options
  • Save soyuka/44e75e8871578d1459ac87f770b00d3c to your computer and use it in GitHub Desktop.
Save soyuka/44e75e8871578d1459ac87f770b00d3c to your computer and use it in GitHub Desktop.
component dynamic angular
@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;
constructor(private _compiler: Compiler,
private _injector: Injector,
private _m: NgModuleRef<any>) {
}
ngAfterViewInit() {
const template = '<span>generated on the fly: {{name}}</span>';
const tmpCmp = Component({template: template})(class {
});
const tmpModule = NgModule({declarations: [tmpCmp]})(class {
});
this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
.then((factories) => {
const f = factories.componentFactories[0];
const cmpRef = this.vc.createComponent(f);
cmpRef.instance.name = 'dynamic';
})
}
// source: https://indepth.dev/posts/1054/here-is-what-you-need-to-know-about-dynamic-components-in-angular
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment