3

I use an api that returns some html. Angular components are used in the html code but not shown in the application.

How can I show an angular component when it is stored as a string?

StackBlitz demo

Niels Prins
  • 535
  • 2
  • 11
  • 1
    No, this is not possible in current Angular version. Upto some extent you can achieve this by exposing your Angular Component as a web component using Angular Elements API, you can refer [this example](https://netbasal.com/understanding-the-magic-behind-angular-elements-8e6804f32e9f) – Pankaj Parkar Jul 28 '22 at 10:21

2 Answers2

1

In general, this goes against how Angular works. There is no Angular feature for [innerHTML]. There are no component selectors there, not even a ViewContainerRef. Instead, because Angular exclusively trusts its own templates, any HTML, CSS, and JS that even appears somewhat suspect is eliminated as a security safeguard. So InnerHTML is outside limits.

You can try to dynamically load components and content with the ViewContainerRef.

Ale_Bianco
  • 387
  • 2
  • 9
0

I think rendering HTML that's returned from the server is not really recommended (you will have to trade off a lot of angular features, like *ngIf etc.). However, if you REALLY want to do it, it is a hard way: https://medium.com/acute-angular/angular-how-to-render-html-containing-angular-components-dynamically-at-run-time-ee8fc907b545

Maybe rethinking the logic a bit, let's say returning an array of components to be displayed, will work flawlessly, since you can string compare and append components directly. Hope it helps!

Sarvesh Chitko
  • 158
  • 1
  • 9