Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get angular2 [innerHtml] to work [duplicate]

Tags:

angular

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

like image 850
LearnToday Avatar asked Feb 01 '17 12:02

LearnToday


2 Answers

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.

like image 122
Cobus Kruger Avatar answered Oct 14 '22 17:10

Cobus Kruger


You have to add attributes inside the tag like this.

<div class="blog-post" [innerHtml]="testhtml"></div>
like image 7
Padhu Avatar answered Oct 14 '22 17:10

Padhu