Search code examples
angularangular2-templateangular-templateangular-pipe

Angular 4+ : is it possible to evaluate a string input to a template as HTML?


Is there a way to evaluate strings passed into a component's template as HTML?

I am passing this:

export const BARS: Blurb = {
  title: "Bars",
  description: "blah blah blah. <a routerLink='/barcades'>Barcades</a>"
}

into this:

<h3>{{blurb.title}}</h3>
<p>{{blurb.description}}</p>

It is currently printing <a routerLink='/barcades'>Barcades</a> literally, without evaluating it.

As a background, I am making a travel blog. All of my pages have the same structure: a bunch of sections of text with headings. In order to avoid code duplication, I created data classes based on a model class like these.

Basically, I created JSONs of all of the literary content for my website, then passed them into multiple instances of a common component. This seemed like a great idea at the time, but now I want to add links(preferably even routerLinks). Is this possible? Maybe using pipes? And is this even an acceptable strategy? I'm curious to know if there's a standard approach in Angular.


Solution

  • What you are looking for is innerHTML property. Something like this: <div [innerHTML]="yourStringObject"> ....

    You might also need to sanitize it first, look at the thread here.