31

I don't know what am doing wrong as no errors are report.

I have a component class

import { Component, OnInit, ViewContainerRef } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
 testhtml = "<p>Hello world</p>";
    constructor(){}

 }

}

And in my template file, I do something like this:

<div class="blog-post">[innerHtml]="testhtml"</div>

But this doesn't seem to work. Is there something else I need to import?

I am using angular-cli "version": "1.0.0-beta.26",

LearnToday
  • 2,762
  • 9
  • 38
  • 67

2 Answers2

74

Angular uses {{property}} for interpolation of values. That is the way that you would display plain text in your div, like so

Solution 1:

<div class="blog-post">{{testhtml}}</div>

But that will write out text, not HTML.

For HTML, you will need to bind to the property

Solution 2:

<div class="blog-post" [innerHtml]="testhtml"></div>

Note I moved the [innerHtml] to inside the div tag.

Leaving out the square brackets would bind to the attribute, so you would need to interpolate again

Solution 3:

<div class="blog-post" innerHtml="{{testhtml}}"></div>

The property binding (Solution 2) is the preferred method.

wittmason
  • 338
  • 2
  • 5
Cobus Kruger
  • 8,338
  • 3
  • 61
  • 106
  • Out of curiosity why is solution two (`innerHtml="{{testhtml}}"`) preferred? – Jamie Street Oct 11 '17 at 23:53
  • @JamieStreet Interpolation (solution 3) is actually converted into property binding (solution 2) - see the bottom of this section: https://angular.io/guide/template-syntax#interpolation---- The Angular documentation encourages the property binding syntax, so that is going to be familiar to other developers you work with. – Cobus Kruger Oct 12 '17 at 10:02
  • 1
    @JaimeStreet I think it's clumsily worded. `[innerHtml]="testHtml"` is the preferred solution. – MgSam Mar 07 '18 at 19:25
  • It would help add clarity to you answer if you would add headers for "Solution 1:" ... "Solution 2:" ... etc. Thanks for the answer. I have added these edits. – wittmason Jun 05 '18 at 13:48
  • 1
    Hi @Cobus Kruger , If I run this code it works fine , But when I use `` It's even not display in html – Sachin Shah Oct 30 '18 at 09:57
  • 1
    Hi @Sachin Shah, you need add pipe to fix this, look this anwer: https://stackoverflow.com/a/41089093/7452985 – izik f Jan 07 '19 at 13:23
8

You have to add attributes inside the tag like this.

<div class="blog-post" [innerHtml]="testhtml"></div>
Padhu
  • 1,590
  • 12
  • 15