33

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",

2
  • 1
    <div class="blog-post" [innerHtml]="testhtml"></div> <= its an attribute not the element content. Commented Feb 1, 2017 at 12:13
  • this worked for me: stackoverflow.com/a/43862386/1048800 Commented May 9, 2017 at 6:16

2 Answers 2

77

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Out of curiosity why is solution two (innerHtml="{{testhtml}}") preferred?
@JamieStreet Interpolation (solution 3) is actually converted into property binding (solution 2) - see the bottom of this section: 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.
@JaimeStreet I think it's clumsily worded. [innerHtml]="testHtml" is the preferred solution.
Hi @Cobus Kruger , If I run this code it works fine , But when I use <input type="text" style="width:200px" name="fname"> It's even not display in html
Hi @Sachin Shah, you need add pipe to fix this, look this anwer: stackoverflow.com/a/41089093/7452985
|
8

You have to add attributes inside the tag like this.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.