Converting String of HTML element to HTML element only Displaying [object HTMLParagraphElement]

Viewed 100

I'm using angular and I'm using this function below to convert the string of a paragraph HTML element received from an API database to convert to HTML

Inside angular component.ts

export class ArtworksComponent implements OnInit {

stringToHTML = function(htmlStr:string) {    

    var wrapper= document.createElement('div');
    wrapper.innerHTML= htmlStr;
    return wrapper.firstChild;
    
}

Inside Component.html

<div class="col-md-4 mb-3" id="container" *ngFor="let artwork of artworks">
        <div >
         {{stringToHTML(artwork.data)}}
        </div>
</div>

The issue I get is its displayed as [object HTMLParagraphElement]
It displays sort of correctly if I simply do

 <p>{{artworks.data.replace("<p>,"").replace("</p>, ""}}</p>

but there are HTML tags inside them and it seems messy chaining replace several times for the other HTML tags across the data.

I console.log(wrapper.firstChild) and the desired HTML element is produced in the console, just won't display correctly on the page itself. Is it something to do with checking to see if it's a safe HTML?

1 Answers

You can try this :

<div class="col-md-4 mb-3" id="container" *ngFor="let artwork of artworks">
        <div [innerHtml]='stringToHTML'>
        </div>
</div>
Related