Marv
Marv

Reputation: 758

Angular2 pass html to component

I am trying to create a component which displays a code example for a given component. The component shall be passed as HTML to the code-example component and be rendered once normally but also have its code displayed below.

When trying to fetch the code from <ng-content> in ngOnInit, Angular already started rendering the component, which means that I do not get the original code between the tags.

Passing the code via input does not work out, as the components may use single and double quotes which will cause problems when binding the data.

What I also tried is passing the code escaped to the component like

<code-example>
    &lt;component>&lt;/component>
</code-example>

To unescape it and render it afterwards, which did not work out for me as I had trouble adding this pre-defined element to the DOM in a way that Angular renders it as a component.

Are there any other methods of dealing with this problem that I might be missing?

Upvotes: 1

Views: 293

Answers (1)

Spitzbueb
Spitzbueb

Reputation: 5891

As @Timothy suggested you may try the <pre> tag.

If you also want to highlight the syntax of your code I can recommend a third party module called ng2-prism.

This is a library that supports multiple languages and is quite easy to use.

Upvotes: 1

Related Questions