Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert strings of HTML into HTML in my template (Angular2/TypeScript)?

I have this object in a dummy-data.ts file. Through a service I pull it successfully in to app.component.ts.

{name:"Object1", 
    prop1: {key:'value', key:'value'},
    password: "P@ssword1",
    htmlText:'<h4>This is THE demo text</h4><p>I want it to display as HTML</p>'
}

Currently app.component.ts looks like this, to start out simply:

@Component({
    selector: 'my-app',
    template: `<h1>{{title}}</h1>
        <p *ngFor="#plot of plots">
            {{plot.personalPanelText.transition}}
        </p>
`,
providers: [PlotService]  
})

The end result is strings instead of HTML. I want the HTML to be code, not text with HTML tags.

I've tried a couple ways and poked around the world wide nets and Angular2 docs, but couldn't find a solution.

Thanks in advance!

like image 547
McPhelpsius Avatar asked Apr 28 '16 17:04

McPhelpsius


People also ask

How do you convert a string in HTML?

The simplest way to do this is to create an element, insert the string into with innerHTML , then return the element. /** * Convert a template string into HTML DOM nodes * @param {String} str The template string * @return {Node} The template HTML */ var stringToHTML = function (str) { var dom = document.

How do I convert TypeScript to plain text in HTML?

var text = html. replace(/<\/?[^>]+>/gi, ' '); The problem with the above approach is that it may fail for malformed HTML or when the HTML content contains entities like dashes, ampersands and other punctuation codes.


1 Answers

You can bind to innerHtml like:

<div [innerHtml]="someProp.htmlText"></div>

Angular does not instantiate any components where the selectors that match tags or attributes in HTML added this way nor will it resolve any bindings (like {{xx}})

See also How to bind raw html in Angular2

like image 128
Günter Zöchbauer Avatar answered Sep 21 '22 20:09

Günter Zöchbauer