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

26,880

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

Share:
26,880
McPhelpsius
Author by

McPhelpsius

I'm a Junior Level JavaScript developer with plans and everything. I'm currently enjoying codeschool.com to learn JavaScript libraries and Git.

Updated on July 09, 2022

Comments

  • McPhelpsius
    McPhelpsius almost 2 years

    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!

  • Ketan Akbari
    Ketan Akbari almost 6 years
    if i want to convert htmlstring to html in component. how can i ?
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    @KetanAkbari Sorry, U don't understand your question. You can't add Angular components rhis way if that is your question.
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    I don't know BsModalService. I'd suggest to create a new question.
  • Ketan Akbari
    Ketan Akbari almost 6 years
    @GünterZöchbauer can we convert string to html in .ts file?