简体   繁体   中英

Trying to convert a Component name from string to Component type in angular 9 gives Type passed in is not ComponentType error

In Template HTML:

<ng-container *ngComponentOutlet="getComponent(item.component); injector: dynamicComponentInjector">
</ng-container>

In.ts file ( THIS WORKS)

getComponent(component){
    return component; //component = 'ProductTitleComponent'
}

But (THIS DOESN'T WORK) since I an getting the value from Database, I am getting it as string like this "ProductTitleComponent". I tried below option but nothing happen.

Getting ERROR: Error: ASSERTION ERROR: Type passed in is not ComponentType, it does not have 'ɵcmp' property.

getComponent(component){
  return component as Component; //component = 'ProductTitleComponent'
}


getComponent(component){
  return JSON.parse(component); //component = 'ProductTitleComponent'
}

I was able to solve the issue by doing this

getComponent(component){
  const comp = { ProductTitleComponent }
  return comp[component];
}

Considering 'ProductTitleComponent' as component value. In this case I have to add a component each time I create one to comp object. Is there any better solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM