savinn
savinn

Reputation: 78

Ionic 2/ angular 2 : string replaced with HTML tag isn't rendered properly

I have an array of contents in my JSON which contain URLs in there as text. I want to find and replace those text URLs with links. What's actually happening? It does replace the URL with <a> tag and proper URL in href="" but still render this <a> tag as text and not as HTML

urlifyContent(){
   let urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
   for (let index = 0; index < this.message.Content.length; ++index){
       this.message.Content[index] = this.message.Content[index].replace(urlRegex,`"<a href='$1'target='_blank'>$1</a>"`);
   }
}

Upvotes: 1

Views: 1409

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71901

According to your comment you are using {{message.Content}} to bind the html you created using your urlifyContent() method. This will not work, because {{}} will parse the value to a string, and not HTML.

To add HTML to your page, you should use the [innerHTML] directive:

<div [innerHTML]="message.Content"></div>

However, it's worth mentioning that this won't parse any angular components or directives or binding present in that HTML snippet. It should just be plain html

Upvotes: 3

Related Questions