Kris
Kris

Reputation: 912

Angular inject component in innerHtml

I'm setting HTML returned from the API in my Angular component:

<div [innerHTML]="content"></div>

content in this example is something like this:

<table>
    <tr>
        <td>[audioPlayer:file.mp3]</td>
    </tr>
</table>

Now I would like to inject the actual component inside the table cell.

If I make a certain container, I can create the component with createComponent:

audioPlayerComponentRef: ComponentRef<AudioPlayerComponent>;
@ViewChild('placeholder', { read: ViewContainerRef }) container;

const factory: ComponentFactory<AudioPlayerComponent> = 
this.componentFactoryResolver.resolveComponentFactory(AudioPlayerComponent);
this.audioPlayerComponentRef = this.container.createComponent(factory);

Then I can inject it into a container in the template:

<div #placeholder></div>

However, going back to my original goal, I can't use such a container, as the component needs to be injected into a specific position into an innerHtml block.

I've been brainstorming all day, but I can't see any way to achieve this.

Upvotes: 0

Views: 1886

Answers (1)

Mvin
Mvin

Reputation: 433

Generally speaking, this is contrary to the way Angular works. [innerHTML] is not parsed for any Angular functionality. No component selectors or even a ViewContainerRef can be found there. Rather, even remotely suspicious HTML, CSS and JS is removed as a security measure as Angular only trusts its own templates.

So InnerHTML is a no-go. But I was in the same boat myself and have written a library to solve this exact problem. With it, you can freely load dynamic components into strings without compromising security. If you're still stuck on this, you might wanna have a look at it.

Upvotes: 1

Related Questions