Created
January 5, 2022 15:59
-
-
Save soyuka/44e75e8871578d1459ac87f770b00d3c to your computer and use it in GitHub Desktop.
component dynamic angular
This file contains 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
@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