0

I'm using a content service with an Angular app. Some of the API queries come back with strings wrapped in html tags ex. "<p>Example value from API</p>". I need to parse these strings and add them to the DOM as html elements.

If I save the API response to question.body.value then doing something like this:

  <div *ngIf="question">
    {{ question.body.value }}
  </div>

Doesn't parse the html. Instead it just results in a div that looks like this (with the wrapping <p> tags printed to the screen):

<div _ngcontent-iws-c79="" class="ng-star-inserted">
 "<p>Example value from API</p>"
</div>

What's the Angular way to parse these into html elements and add them to the DOM? I've tried the Angular Renderer2 and the native Javascript DOMParser but neither of these seem to be the right approach.

gp22
  • 11
  • 2

1 Answers1

0

Via typescript:

@ViewChild('elementRef') public elementRef: ElementRef;
public htmlString = '<b>Random string</b>';
public addHTML(): void {
  this.elementRef.nativeElement.innerHTML = htmlString;
}

Via html:

<div #elementRef [innerHtml]="htmlString"></div>
BingBong
  • 120
  • 1
  • 6