Angular 从 JSON (API) 加载动态组件

Angular Dynamic Component Loading from JSON (API)

我正在尝试从 API 调用的响应中动态加载组件。

假设我有 3 个 components/widgets A、B 和 C。根据 API 调用的响应,我必须加载 A、B、C 或它们的任意组合任何顺序(比如按 C 和 B 的顺序加载它们)。有点像客户端的CMS。

我想到的一个解决方案是使用从 API 获取带有组件 ID 的 HTML 代码并使用 [innerHtml].

是否有任何替代解决方案,我可以从 API 中获取 widget/component 的列表,并将它们动态加载到 Angular 中?

有一个概念叫做“ComponentFactoryResolver”。希望这对您的案件有所帮助。

更多详情: https://angular.io/guide/dynamic-component-loader#resolving-components

I thought of was using getting HTML code with ids of components from the API and using [innerHtml]

你为什么不使用内容投影而不是创建多个组件呢?创建一个组件并在子组件中使用 ng-content 传递 html。您可以查看 here 了解更多详情。

here any alternative solutions where I can get a list of widget/component from API, and load them in Angular Dynamically?

您可以使用 angular 中的 ComponentFactoryResolver ,这将帮助您完成它。您需要获取 viewContainerRef 并使用 ComponentFactoryResolver 动态创建一个组件并注入它。

This 是一个很好的参考,您可以按照它来做。