0

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.

1
  • I’m afraid you have to rethink your approach. You cannot have a functional angular component inside innerHtml.. Commented Jul 14, 2020 at 16:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

[innerHTML] can have Angular functionality through use of createCustomElement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.