I want to display a angular-component by inserting its name as a string.I tried the way through viewContainerRef, but it is not working. I load the component string name from a json and then I want to render it as an component, which is already created in the root level of the app.
Overview:
This is a json-file with the desired componentName:
{
"planeGeo": {
"topics": {
"Basics": {
"Intro":
{
"title": "Intro to areas",
"routerLink": "Intro",
"htmlCode": "assets/html/plane1.html",
"componentName" : "<app-lorem></app-lorem>"
},
"Calculation":
{
"title": "Calculation of areas",
"routerLink": "Calc",
"htmlCode": "assets/html/plane2.html",
"componentName" : "<app-test></app-test>"
}
}
}
For now I load the path of an html-file with this method:
getCurrentContent() {
const jsonPath = `assets/models/${this.currentSubject}.json`;
this.http.get<any>(jsonPath).subscribe((data) => {
const htmlPath =
data[this.currentSubject]['topics'][this.topic][this.subtopic][
'htmlCode'
];
if (htmlPath) {
this.http
.get(htmlPath, { responseType: 'text' })
.subscribe((htmlData) => {
this.currentContent =
this.sanitizer.bypassSecurityTrustHtml(htmlData);
});
} else {
console.error('HTML-Code nicht gefunden.');
}
});
}
which is then inserted in the corresponding html-file:
<div [innerHTML]="currentContent"></div>
What I want to do is loading a complete compononent instead of a single html-file, because of the limitations with css and js-logic.
I tried the following:
getCurrentContentAsComponent() {
const jsonPath = `assets/models/${this.currentSubject}.json`;
this.http.get<any>(jsonPath).subscribe((data) => {
const componentName =
data[this.currentSubject]['topics'][this.topic][this.subtopic][
'componentName'
];
console.log(componentName);
if (componentName) {
this.loadComponent(componentName);
} else {
console.error('Komponentenname nicht gefunden.');
}
});
}
loadComponent(componentName: any) {
const componentRef = this.viewContainerRef.createComponent(componentName);
console.log(componentRef);
}
, but here I get error msgs that my passed value is not a component (what is true, because it is a string at this moment).
The component is already created, i.e. <app-lorem>.
The console output says that the string is <app-lorem></app-lorem>, but it its component isn't rendered.
My question is: How can I handle the string name to be rendered as an component?