Skip to content

Instantly share code, notes, and snippets.

@coderkan
Created March 15, 2020 18:03
Show Gist options
  • Save coderkan/eb2e5d60c921f2432294d53aa731668b to your computer and use it in GitHub Desktop.
Save coderkan/eb2e5d60c921f2432294d53aa731668b to your computer and use it in GitHub Desktop.
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'dynamic-comp-app';
frameworks: FrameworkItem[];
@ViewChild(FrameworkDirective, { static: true }) frameworkHost: FrameworkDirective;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
ngOnInit(): void {
this.frameworks = this.getFrameworkList();
this.loadDynamicComponentsWithIndex(0);
}
loadDynamicComponentsWithIndex(ind: any) {
const frameworkItem = this.frameworks[ind];
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(frameworkItem.component);
const viewContainerRef = this.frameworkHost.viewContainerRef;
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory);
(<FrameworkComponent>componentRef.instance).data = frameworkItem.data;
}
getFrameworkList() {
return [
new FrameworkItem(AngularComponent, { name: 'Angular' }),
new FrameworkItem(VueComponent, { name: 'VueJS' }),
new FrameworkItem(ReactComponent, { name: 'ReactJS' })
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment