user1893354
user1893354

Reputation: 5938

How to show custom html tags as plain text inside innerHtml

I have a sort of strange use-case in Angular 2 where I have some content that contains regular html tags as well as custom html tags. I want to render the regular html tags and show the custom html tags as plain text. For example

the <CUSTOM_TAG>boy</CUSTOM_TAG> went to the <b>store</b>

should have <CUSTOM_TAG>boy</CUSTOM_TAG> appearing as plain text just as you see it above, however <b>store</b> should appear as store i.e. the bold tag is actually rendered.

When I try the usual way of inserting html i.e.

<div [innerHtml]="myHtml"></div>

I get a sanitization error because of the custom tag. When I fix the sanitization error as was done here it just strips out the custom tags which I also don't want. Is showing the custom tags as plain text and rendering the regular html tags possible?

Upvotes: 2

Views: 875

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73761

If all the possible custom tags are known, you can encode them before passing the string to the [innerHTML] binding. The method encodeCustomTags in the following code snippet uses a regular expression to replace <customTag> with &lt;customTag&gt;:

private customTags = [
  "CUSTOM_TAG",
  "otherTag",
];

myHtml = this.encodeCustomTags("the <CUSTOM_TAG>boy</CUSTOM_TAG> went to the <b>store</b>");

private encodeCustomTags(html: string): string {
  let regex: RegExp;
  for (let tag of this.customTags) {
    regex = new RegExp(`<(/?)${tag}>`, "gi");
    html = html.replace(regex, `&lt;$1${tag}&gt;`)
  }
  return html;
}

See this stackblitz for a demo.

Upvotes: 1

Related Questions